【问题标题】:How I can I unit test that a function inside another function was called?如何对另一个函数中的函数进行单元测试?
【发布时间】:2017-11-14 14:12:36
【问题描述】:

如何对另一个函数中的函数进行单元测试?我无法更改源代码,所以我需要按原样进行测试。

我该怎么做?这是我的代码:

function B(){ console.log('function b'); }

function A(){
    B();
}  

茉莉花测试:

it('should check function B in function A was called', function () {
    spyOn(window, 'B');
    A();
    expect(B).toHaveBeenCalled();
});

【问题讨论】:

  • 我想添加一个答案,但我认为这主要是意见。对我来说,这是一种代码味道。单元测试独立于程序的其余部分测试单个单元(模块、函数、类)。本质上,他们测试给定一个输入,你得到一个输出。我建议移动嵌套调用并改用组合和经过测试的组合工具。类似于pipepipe(a,b)(inputToA) 将为您提供 3 个经过全面测试的函数,没有模拟或间谍。这不是许多人持有的观点,因此请持保留态度。

标签: javascript unit-testing jasmine


【解决方案1】:

间谍

Jasmine 具有称为间谍的测试双重功能。间谍可以存根任何 函数并跟踪对它的调用和所有参数。间谍只存在 在定义它的 describe 或 it 块中,并将 每个规格后删除。有特殊的匹配器进行交互 与间谍。 Jasmine 2.0 已更改此语法。这 如果调用了间谍,toHaveBeenCalled 匹配器将返回 true。这 如果参数列表,toHaveBeenCalledWith 匹配器将返回 true 匹配任何记录的对间谍的调用。

 describe("A spy", function() {
  var foo, bar = null;

  beforeEach(function() {
    foo = {
      setBar: function(value) {
        bar = value;
      }
    };

    spyOn(foo, 'setBar');

    foo.setBar(123);
    foo.setBar(456, 'another param');
  });

  it("tracks that the spy was called", function() {
    expect(foo.setBar).toHaveBeenCalled();
  });

  it("tracks all the arguments of its calls", function() {
    expect(foo.setBar).toHaveBeenCalledWith(123);
    expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
  });

  it("stops all execution on a function", function() {
    expect(bar).toBeNull();
  });
});

【讨论】:

    猜你喜欢
    • 2019-04-15
    • 2018-11-20
    • 2017-01-18
    • 1970-01-01
    • 2014-02-08
    • 2017-01-03
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多