【问题标题】:How to fix function has already been spied on error in Jasmine如何修复功能已在 Jasmine 中发现错误
【发布时间】:2019-05-13 18:50:08
【问题描述】:

我有 3 个测试,每个测试不同的方法。

it('test function1', function() {
   spyOn(document, 'getElementById');
   // ... some code to test function1
   expect(document.getElementById).toHaveBeenCalled();

 });

it('test function2', function() {
   spyOn(document, 'getElementById');
   // ... some code to test function2
   expect(document.getElementById).toHaveBeenCalled();

 });

it('test function3', function() {
   spyOn(document, 'getElementById');
   // ... some code to test function3
   expect(document.getElementById).toHaveBeenCalled();    
 });

但是当我运行这些测试时,我收到以下错误:getElementById has already been spied upon。有人可以解释为什么即使间谍在不同的测试套件中我也会收到此错误以及如何修复它。

【问题讨论】:

  • 你为什么要监视和测试原生 JS/浏览器代码?我认为这些函数在被调用时会起作用是安全的。
  • 因为test没有加载HTML文件,所以js文件中的document.getElementById('').style等会报错。
  • 您可能应该测试某个元素是否存在,而不是测试是否调用了本机浏览器代码。

标签: javascript jasmine karma-jasmine jasmine-jquery jasmine2.0


【解决方案1】:

一旦你对一个方法进行了一次监视,就不能再次对其进行监视。如果您只想检查它是否在每个测试中被调用,只需在测试开始时创建 spy,然后在 afterEach 中重置调用:

     spyOn(document, 'getElementById');

     afterEach(() => {
       document.getElementById.calls.reset();
     });

     it('test function1', function() {
       // ... some code to test function1
       expect(document.getElementById).toHaveBeenCalled();

     });

    it('test function2', function() {
       // ... some code to test function2
       expect(document.getElementById).toHaveBeenCalled();

     });

    it('test function3', function() {
       // ... some code to test function3
       expect(document.getElementById).toHaveBeenCalled();    
     });

【讨论】:

  • 澄清一下,您只能对单个对象的方法进行一次监视。
【解决方案2】:

回复晚了,但是,如果有人试图多次监视同一个函数但返回值不同,你可以使用

it('test function', function() {
   // spy and return data
   spyOn(serviceName,'functionName').and.returnValue(data);
   expect(serviceName.functionName).toHaveBeenCalled();
   
   // spy and return newData
   serviceName.functionName = jasmine.createSpy().and.returnValue(newData);
   expect(serviceName.functionName).toHaveBeenCalled();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2019-06-27
    相关资源
    最近更新 更多