javascript - Jasmine spy 功能在回调中不起作用

标签 javascript unit-testing callback jasmine

如果在回调函数中调用该方法,则在对象上使用 spy On似乎会失败。 jasmine 不会注意到回调中对该方法的任何调用。

请参阅下面的代码,我在 child.print() 方法上创建了一个 spy 。如果我在回调(setTimeout)中调用 child.print(),它不起作用:

it('test', function() {
    const child = {
        print: function() {
            console.log('child');
        }
    };
    spyOn(child, 'print');
    const parent = {
        callChildInCallback: function() {
            setTimeout(()=> child.print(), 1000);
        }
    };
    parent.callChildInCallback();
    expect(child.print.calls.count()).toEqual(1);
});

此操作将失败,并出现错误“预期 0 等于 1。”

但是,如果我直接调用它,它就会起作用:

it('test', function() {
    const child = {
        print: function() {
            console.log('child');
        }
    };
    spyOn(child, 'print');
    const parent = {
        callChild: function() {
            child.print();
        }
    };
    parent.callChild();
    expect(child.print.calls.count()).toEqual(1);
});

我试图在回调中设置一个断点,似乎我们正在测试的函数周围的 spy 包装消失了,这就是表面上的原因。有人可以解释为什么会发生这种情况以及正确的方法吗?

感谢您的阅读~

最佳答案

您需要使用 Jasmine clock使用超时函数

it('test', function() {
jasmine.clock().install();
  const child = {
    print: function() {
      console.log('child');
    }
  };
  spyOn(child, 'print').and.callThrough();
  const parent = {
    callChildInCallback: function() {
      setTimeout(function() {
        child.print()
      }, 1000);
    }
  };
  parent.callChildInCallback();
  jasmine.clock().tick(1001);
  expect(child.print.calls.count()).toEqual(1);
});

关于javascript - Jasmine spy 功能在回调中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40688401/

相关文章:

c++ - GoogleTest 和内存泄漏

Java简单回调

javascript - 拖拽文件上传,$_FILES出错

javascript - 使用 Jquery 使用 1 个按钮一次切换多个 div

javascript - ng-model 值始终未定义

使用 GeoDjango + PostGIS 进行 Django 测试

python - 如何以 Tornado 的风格为 Cyclone 编写测试?

javascript - 请帮我删除 Exploring ES6 中的这个例子

javascript - 尝试使用 Jquery 在 WordPress 页面上显示 YouTube 点击次数

javascript - 使用其上下文调用原始回调函数