【问题标题】:Jasmine spyOn not working for window functionJasmine spyOn 不适用于窗口功能
【发布时间】:2019-05-08 00:10:11
【问题描述】:

我正在尝试监视 window.alert。我已经监视了窗口的警报功能,但它仍然说它必须被监视。 我的组件有

method1(){
method2();
}
method2{
if(some condition){
alert('hello');
}
}

我的单元测试:

it('it should say hello', () => {
 spyOn(component, 'method1').and.callThrough();
   spyOn(window, 'alert');
component.method1();
expect(window.alert).toHaveBeenCalledWith('hello');

}

错误是 预期的间谍警报已使用 ['hello'] 调用,但从未调用过

【问题讨论】:

  • 你能给出描述的错误的有效复制吗?因为你的代码应该可以工作。

标签: javascript angular unit-testing jasmine angular6


【解决方案1】:

因为你发现了 method1() 并且你的警报是从 method2() 调用的。所以监视 method2() 将通过测试。 下面的代码应该运行:

 it('it should say hello', () => {
         spyOn(component, 'method2').and.callThrough();
         spyOn(window, 'alert');
         component.method1();
         expect(window.alert).toHaveBeenCalledWith('hello');

    }

【讨论】:

    猜你喜欢
    • 2020-12-27
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多