Jasmine spyOn on function和返回的对象

psa*_*ski 9 unit-testing jasmine angularjs meteor angular-mock

我正在使用具有角度的MeteorJS并且想要测试控制器.我的控制器使用$ reactive(this).attach($ scope).如果调用此方法,我需要检查.

我为间谍创造了类似的东西:

var $reactive = function(ctrl) {
    return {
        attach:function(scope) {}
    }
};
Run Code Online (Sandbox Code Playgroud)

所以我可以这样称呼它:

$reactive('aaa').attach('bbb');
Run Code Online (Sandbox Code Playgroud)

我怎么能在测试中做到这一点?

spyOn($reactive, 'attach');
Run Code Online (Sandbox Code Playgroud)

不行.我得到错误:attach()方法不存在

以及如何检查它是否被调用?这是好的电话?

expect($reactive).toHaveBeenCalledWith(controller);
Run Code Online (Sandbox Code Playgroud)

如何用args(范围)调用函数attach?

Rau*_*cco 4

您需要模拟该$reactive组件。spyObj将其替换为在测试范围内返回 的间谍。$reactive然后触发使该方法运行和测试的内容。

var reactiveResult = jasmine.createSpyObj('reactiveResult', ['attach']);
var $reactive = jasmine.createSpy('$reactive').and.returnValue(reactiveResult);
var controller = {};
    beforeEach(function () {
      module(function ($provide) {
        $provide.factory('$reactive', $reactive);
      });
      module('yourAppModule');
    });

it('Should call attach', function () {
  $reactive(controller).attach();
  expect($reactive).toHaveBeenCalledWith(controller);
  expect(reactiveResult.attach).toHaveBeenCalled();
}) ;
Run Code Online (Sandbox Code Playgroud)

$reactive您也可以向控制器依赖项提供间谍:

var reactiveResult = jasmine.createSpyObj('reactiveResult', ['attach']);
var $reactive = jasmine.createSpy('$reactive').and.returnValue(reactiveResult);
var ctrl;
    beforeEach(inject(function ($controller) {
      ctrl = $controller('YourController', {$reactive: $reactive });
    }));

it('Should call attach', function () {
  //ctrl.triggerThe$reactiveCall
  expect($reactive).toHaveBeenCalledWith(ctrl);
  expect(reactiveResult.attach).toHaveBeenCalled();
}) ;
Run Code Online (Sandbox Code Playgroud)