我正在将MeteorJS与angular一起使用,并想测试 Controller 。我的 Controller 使用$ reactive(this).attach($ scope)。我需要检查是否调用了此方法。

我为 spy 创建了类似的东西:

var $reactive = function(ctrl) {
    return {
        attach:function(scope) {}
    }
};

所以我可以这样称呼它:
$reactive('aaa').attach('bbb');

我如何在测试中做到这一点?
spyOn($reactive, 'attach');

不起作用我得到了错误:attach()方法不存在

以及如何检查它是否被调用?
这是好电话吗?
expect($reactive).toHaveBeenCalledWith(controller);

以及如何检查使用args(作用域)调用了函数attach?

最佳答案

您需要模拟$reactive组件。将其替换为在测试范围内返回spyObj的 spy 。然后触发使$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();
}) ;

您也可以将$reactive spy 提供给 Controller 依赖项:
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();
}) ;

10-07 13:29
查看更多