首页 > 解决方案 > 如何修复功能已在 Jasmine 中发现错误

问题描述

我有 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. 有人可以解释为什么即使间谍在不同的测试套件中我也会收到此错误以及如何修复它。

标签: javascriptjasminekarma-jasminejasmine-jqueryjasmine2.0

解决方案


一旦您对某个方法进行了一次监视,就不能再次对其进行监视。如果您只想检查它是否在每个测试中被调用,只需在测试开始时创建间谍,然后重置调用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();    
     });

推荐阅读