【问题标题】:Spy on a function which is called by another function in Jasmine监视 Jasmine 中另一个函数调用的函数
【发布时间】:2016-03-04 05:19:50
【问题描述】:

如何监视Jasmine 中另一个函数调用的函数?

如果我打电话给this.bar(),期望是真的,但我对此不感兴趣。

规格

import * as src from './src;

describe('app', () => {
  it('should call bar', () => {
    spyOn(src, 'bar');
    src.foo();
    expect(src.bar).toHaveBeenCalled();
  });
});

来源

function foo() {
  bar();
}

function bar() {
  console.log('bar');
}

export {
  foo,
  bar,
};

【问题讨论】:

  • 你用的是什么版本的茉莉花?
  • @leobelizquierdo 版本 2.4.1

标签: javascript node.js unit-testing jasmine


【解决方案1】:

在 Jasmine 中,当您使用 spyOn 时,它会模拟该函数并且不执行任何操作。如果您想测试更多的函数调用,您需要拨打and.callThrough(),如下所示,请尝试

spyOn(src, 'bar').and.callThrough();

【讨论】:

    【解决方案2】:

    检查这个问题:AngularJS - How to test if a function is called from within another function?。似乎正在测试的函数 (bar) 需要使用与正在被 spyOn 的函数 (src.bar) 相同的引用来调用。你需要在foo 内部引用src.bar,所以你必须使用this.bar

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      • 2016-11-21
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多