【问题标题】:toHaveBeenCalled() not working correctly Angular Unit TestingtoHaveBeenCalled() 无法正常工作 Angular 单元测试
【发布时间】:2022-01-14 14:00:18
【问题描述】:

我的角度组件中有以下对象:

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

问题:

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

预期的间谍没有被调用。

通过调试,我发现它失败了,因为最初从 fixture.detectChanges() ngOnInit 根据条件从那里调用 callSomething() 也被调用。

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

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

【问题讨论】:

  • 我认为您需要重置间谍,尝试使用此方法重置:stackoverflow.com/a/54419453/7365461。我认为您应该在beforeEach 中重置间谍,以便更易于管理。
  • delete _user.user["id"] 直接干扰组件类。在什么情况下实际使用可能会发生这种情况?你也不应该监视你应该测试的东西; callSomething 做了什么?如上所述,您可以重置模拟以断言该方法没有被调用再次,但为了正确测试案例需要更多更改(我们需要更多上下文来提供有关它们的详细信息' d是)。
  • @AliF50 感谢您的解决方案有效。
  • @jonrsharpe 如果我不监视用户对象,我该如何更改它的值?以及如何检查其他测试用例的可能性? (例如:keys.length > 0,keys.length
  • 再次,在实际使用的什么情况下可能会发生这种情况? call something 真的是做什么的?如果没有组件的minimal reproducible example,我们无法告诉您如何实际测试它。但是 .length 意味着什么?

标签: angular unit-testing jasmine angular11


【解决方案1】:

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

解决方案:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    相关资源
    最近更新 更多