I have this test, perfectly running:
it('The click on the logo must call goTo("home")', () => {
spyOn<LayoutComponent, any>(component, 'goTo');
let logo = fixture.debugElement.query(
By.css('#logoVitisoft')
).nativeElement;
logo.click();
fixture.whenStable().then(() => {
expect(component.goTo).toHaveBeenCalledWith('home');
});
});
And this one (which is barely the same than the previous one) triggering the error :
it('The click on Dashboard must call goTo(home)', () => {
spyOn<LayoutComponent, any>(component, 'goTo');
let button = fixture.debugElement.query(
By.css('#dashboardElem')
).nativeElement;
button.click();
fixture.whenStable().then(() => {
expect(component.goTo).toHaveBeenCalledWith('home'); /* ERROR SPAWN HERE */
});
});
Precisions : both tests passed if they are called with "fit", I have disabled the randomness of the test and I keep executing ng test with the same seed. The error spawn when I call the 2nd test as "it" : "Expected a spy, but got Function."
EDIT : here are the beforeEach
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [RouterTestingModule, HttpClientModule],
declarations: [LayoutComponent],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(LayoutComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
What am I missing?
CodePudding user response:
fixture.whenStable()
returns a Promise, which is asynchronously executed. This means your test is already finished and cleaned up when expect()
is executed.
Try using the done()
function for these kinds of tests:
it('The click on Dashboard must call goTo(home)', (done) => {
spyOn<LayoutComponent, any>(component, 'goTo');
let button = fixture.debugElement.query(
By.css('#dashboardElem')
).nativeElement;
button.click();
fixture.whenStable().then(() => {
expect(component.goTo).toHaveBeenCalledWith('home');
done();
});
});