我怎样才能测试另一个函数内的函数是否被调用? [英] How I can I unit test that a function inside another function was called?

查看:130
本文介绍了我怎样才能测试另一个函数内的函数是否被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能测试另一个函数内的函数是否被调用?我无法更改源代码,因此我需要按原样进行测试。

How I can I unit test that a function inside another function was called? I can't change the source code, so I need to test this as-is.

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

How can I do this? Here's my code:

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();
});


推荐答案


Spies

Spies

Jasmine有称为间谍的测试双重功能。间谍可以存根任何
函数并跟踪对它的调用和所有参数。间谍只在描述它的描述或块中存在
,并且在每个规范之后将被删除
。有一些特殊的匹配器用于与间谍互动
。 Jasmine 2.0的语法已更改。如果调用间谍,
toHaveBeenCalled匹配器将返回true。如果参数列表
匹配任何记录的间谍调用,
toHaveBeenCalledWith匹配器将返回true。

Jasmine has test double functions called spies. A spy can stub any function and tracks calls to it and all arguments. A spy only exists in the describe or it block in which it is defined, and will be removed after each spec. There are special matchers for interacting with spies. This syntax has changed for Jasmine 2.0. The toHaveBeenCalled matcher will return true if the spy was called. The toHaveBeenCalledWith matcher will return true if the argument list matches any of the recorded calls to the spy.



 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();
  });
});

这篇关于我怎样才能测试另一个函数内的函数是否被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆