toHaveBeenCalled() 无法正常工作 Angular 单元测试

toHaveBeenCalled() not working correctly Angular Unit Testing

我的 angular 组件中有以下对象:

let _user = {user: { id: 1 } };

ngOnInit(){
   if(Object.keys(_user.user).length > 0){
       callSomething()
   }
}

=> 现在该组件 spec.ts 文件

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.
    });
});

问题:

在这里,当我 运行 测试用例失败时说

Expected spy not to have been called.

通过调试,我发现它失败了,因为最初从 fixture.detectChanges() ngOnInit 根据条件 callSomething( ) 也接到了电话。

因此,当测试用例 运行 时,它已经调用了 callSomething()。所以,它失败了。

我该怎么做才能正确测试案例?

正如@AliF50 在问题评论中所建议的那样,休息该方法的调用对我有用。

解法:

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();
});