Reputation: 137
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.
Upvotes: 1
Views: 7574
Reputation: 911
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');
});
}));
Upvotes: 3
Reputation: 1659
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');
}));
Upvotes: 1