1

I'm writing this unit test to verify when clicking back button, then it will show the login page.

The HTML script below is the back button.

<button [routerLink]="[url_sep + login]" class="btn bigBtn btn-gray" keep-width type="button">
          Back
</button>

The script below is the unit test which I want to execute.

let de: DebugElement;
let el: HTMLElement;

it('should open login page when click back button', () => {
    de = fixture.debugElement.query(By.css('.btn-gray'));
    el = de.nativeElement;
    el.click();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('p').textContent).toContain('Welcome');
  });

After I ran this unit test, the button wasn't clicked, because it verified 'Welcome' word in the same page not in the log in page.

2 Answers 2

3

The click event probably isn't ready yet, so you have to wait for it. You can use fixture.whenStable() for this.

See the following example:

it('should', async(() => {


  let button = fixture.debugElement.query(By.css('.btn-gray'));
  button.click();

  fixture.whenStable().then(() => {
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('p').textContent).toContain('Welcome');
  });
}));

See Angular Docs on testing.

Sign up to request clarification or add additional context in comments.

2 Comments

I got SyntaxError if I use querySelector. However, the button still isn't clicked, after I use fixture.whenStable().
Updated the code sample with the correct QuerySelector
2

I would prefer using the method provided by the DebugElement to invoke the event instead of calling it directly on the native element. But either way, it is important to once wait until the event is handled and then call a fixture.detectChanges() in order to update the template to assert new rendered elements.

So it would be something like this:

it('should open login page when click back button', fakeAsync(() => {
    de = fixture.debugElement.query(By.css('.btn-gray'));
    el = de.triggerEventHandler('click', null);

    tick(); // this is important
    fixture.detectChanges(); // this is important

    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('p').textContent).toContain('Welcome');
  }));

2 Comments

The button still isn't click, after I use tick(); fixture.detectChanges(); and fakeAsync.
Ah yes. I see. Your button doesn‘t have a click listener at all. So it does nothing on click. What are you trying to test? The routing?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.