When you testing Component rendering, you often needs to call:
fixture.detectChanges();
For example:
it('should display original title', () => {
fixture.detectChanges();
expect(el.textContent).toContain(comp.title);
}); it('should display a different test title', () => {
comp.title = 'Test Title';
fixture.detectChanges(); // After change the prop of comp instance, call detectChanges()
expect(el.textContent).toContain('Test Title');
});
You can also set auto change detection:
import { ComponentFixtureAutoDetect } from '@angular/core/testing';
Add to providers:
TestBed.configureTestingModule({
declarations: [ BannerComponent ],
providers: [
{ provide: ComponentFixtureAutoDetect, useValue: true }
]
})
Tests wit auto change detection:
it('should display original title', () => {
// Hooray! No `fixture.detectChanges()` needed
expect(el.textContent).toContain(comp.title);
}); it('should still see original title after comp.title change', () => {
const oldTitle = comp.title;
comp.title = 'Test Title';
// Displayed title is old because Angular didn't hear the change :(
expect(el.textContent).toContain(oldTitle);
}); it('should display updated title after detectChanges', () => {
comp.title = 'Test Title';
fixture.detectChanges(); // detect changes explicitly
expect(el.textContent).toContain(comp.title);
});