【问题标题】:Angular - Jasmine: Testing immediately invoked functions inside a directive controllerAngular - Jasmine:在指令控制器中测试立即调用的函数
【发布时间】:2016-08-11 21:44:57
【问题描述】:

假设我有一个类似的指令:

.directive('myDir', function(TemplateHandler){
  return {
    ...
    controller: function(ExploreCmd){
      this.foo = {
        bar: function(){...}
      };

      this.foo.bar();
    }
  }
});

我想测试一下,当指令被加载时,this.foo.bar() 函数已经被调用,我该如何实现呢?

我试过了:

beforeEach(inject(function($compile, $rootScope){
  scope = $rootScope.$new();
  element = angular.element('<js-shell></js-shell>');
  $compile(element)(scope);
  scope.$digest();
  isolatedScope = element.isolateScope().vm;
  spyOn(isolatedScope.foo, 'bar');
}));

it('should register the explore command', () => {
  expect(isolatedScope.foo.bar).toHaveBeenCalled();
});

但问题是spyOn(isolatedScope.foo, 'bar');是在isolatedScope.foo.bar被调用之后被调用的,所以测试失败了。

【问题讨论】:

    标签: angularjs testing angularjs-directive jasmine spy


    【解决方案1】:

    我认为在这种情况下你不能。在创建 foo 和调用 foo.bar 之间没有任何时刻,您可以抓住它来用间谍替换 foo.bar。

    当您的 spyOn 函数运行时,foo.bar() 已被调用并返回。

    如果 foo.bar 有设置 foo.baz 为 true 的副作用,你可以看看。

    【讨论】:

    • 谢谢艾米,我也有同样的感觉。我会继续检查副作用。我想到的另一个选择是将foo.bar 移动到服务中,并在组件中调用该函数,以便我可以模拟/监视它...
    • 或者稍后调用它以响应其他一些事件。
    猜你喜欢
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 2015-01-18
    • 2015-12-30
    相关资源
    最近更新 更多