茉莉花spyOn不适用于窗口功能

时间:2018-12-06 10:12:22

标签: javascript angular unit-testing jasmine angular6

我试图在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']调用,但从未调用过

1 个答案:

答案 0 :(得分:0)

因为您监视了method1(),并且正在从method2()调用警报。因此,对method2()进行监视将通过测试。 以下代码应运行:

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

    }