AngularJS,从茉莉期间推出测试控制器上的prevent init方法 [英] AngularJS, prevent init method on controller from launching during jasmine tests

查看:99
本文介绍了AngularJS,从茉莉期间推出测试控制器上的prevent init方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有实例上推出了init()方法的控制器。
它做了一堆东西这是我在实际环境中的应用程序非常有用,但是这与我的单元测试间谍弄乱了。

I have a controller with a init() method launched on instantiation. It does a bunch of things which are useful for my app in a live environment, but that messes up with my unit-tests spies.

实例在单元测试环境中的控制器时,有没有一种方法,以prevent其呼叫?
或者,也许一个办法把它自动在Web应用程序上下文调用未做明确调用init()在控制器code的结束?

Is there a way to prevent its call when instantiating the controller in the unit-test environment ? Or maybe a way to have it called automatically in the webapp context without making an explicit call to init() at the end of the controller code ?

推荐答案

这是一个有点难以提供precise指导没有看到现场code例子(这就是为什么它通常是一个好主意,提供有一个模板茉莉花测试),但它听起来像你的 A普拉克的init 方法执行应该根据不同的环境是不同的一些设置的逻辑。如果是这样前进的道路将是这个初始化逻辑封装到一个专门的服务,并在测试过程中模拟这种服务(这正是@Joe Dyndale是在暗示)。

It is a bit hard to provide precise guidance without seeing a live code example (this is why it is usually a good idea to provide a plunk that has a template for Jasmine tests) but it sounds like your init method executes some setup logic that should be different depending on the environment. If so the way to move forward would be to encapsulate this initialization logic into a dedicated service and mock this service during testing (this is exactly what @Joe Dyndale is suggesting).

只要你的控制器看起来像如下:

Provided that your controller looks like follows:

app.controller('MainCtrl', function($scope) {
  $scope.init = function() {
    //something I really don't want to call during test
    console.log("I'm executing");
  };
});

它可以重构为:

app.factory('InitService', function() {
  return {
    init = function() {
      //something I really don't want to call during test
      console.log("I'm executing");
    }
  };
});

app.controller('MainCtrl', function($scope, InitService) {
  InitService.init();
});

,然后用嘲讽的测试可能看起来像这样:

and then the test with mocking could look like so:

describe('Testing an initializing controller', function() {
  var $scope, ctrl;

  //you need to indicate your module in a test
  beforeEach(module('plunker'));
  beforeEach(module(function($provide){
    $provide.factory('InitService', function() {
      return {
        init: angular.noop
      };
    });
  }));
  beforeEach(inject(function($rootScope, $controller) {
    $scope = $rootScope.$new();
    ctrl = $controller('MainCtrl', {
      $scope: $scope
    });
  }));

  it('should test sth on a controller', function() {
    //
  });
});

最后这里是plunker现场code:
<一href=\"http://plnkr.co/edit/fgZMJNfPQeKLt0IEva7d?p=$p$pview\">http://plnkr.co/edit/fgZMJNfPQeKLt0IEva7d?p=$p$pview

这篇关于AngularJS,从茉莉期间推出测试控制器上的prevent init方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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