I have following object in my angular component:
let _user = {user: { id: 1 } };
ngOnInit(){
if(Object.keys(_user.user).length > 0){
callSomething()
}
}
=> now for that component spec.ts file
describe("",() => {
let _user = { user: {id: 1} };
let component: TempComponent;
let fixture: ComponentFixture<TempComponent>;
beforeEach(() => {
... component configuration
fixture.detectChanges();
// this will call lifecycle methods and from there component's callSomething() will also get called.
});
it("should not call callSomething() if user properties == 0", () => {
delete _user.user["id"];
// now _user will be only { user: {} }
component.ngOnInit(); // or can call fixture.detectChanges();
expect(component.callSomething).not.toHaveBeenCalled();
// as now the user object will be empty, but because of beforeEach's detectChanges call, it is failing.
});
});
Problem:
Here, when I run the test case it fails saying
Expected spy not to have been called.
with debugging, I figured out that it is failing because initially from fixture.detectChanges() ngOnInit called from there based on the condition callSomething() also got called.
So, when the testcase runs it has already called callSomething(). So, it is failing.
What shall I do, to test the case properly?
CodePudding user response:
As @AliF50 suggested in question's comment, resting the calls of the method worked for me. stackoverflow.com/a/54419453/7365461.
Solution:
it("should not call callSomething() if user properties == 0", () => {
component.callSomethig.calls.reset();
// Note: callSomething should be part of spy object. Then only `calls` property will be applied to it.
delete _user.user["id"];
component.ngOnInit();
expect(component.callSomething).not.toHaveBeenCalled();
});
