How I can I unit test that a function inside another function was called?

本小妞迷上赌 提交于 2019-12-24 12:13:49

问题


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

Jasmine test:

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

回答1:


Spies

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


来源:https://stackoverflow.com/questions/47287942/how-i-can-i-unit-test-that-a-function-inside-another-function-was-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!