如何在单元测试时在角度1.5中添加$ componentController的依赖项

时间:2016-10-06 12:26:25

标签: angularjs testing dependencies components

我想在组件中向Controller添加依赖项:

这是我的组件:

angular
  .module('app')
  .component('myComponent', {
    template: '<div>some content</div>',
    controller: ["$routeParams", function ($routeParams) {
       var ctrl = this;
       ctrl.myId = $routeParams.id;
  });

现在我只想测试如下:

describe("spec for myComponent", function () {

  var $componentController;
  var $routeParams;

  beforeEach(module('app'));
  beforeEach(inject(function (_$componentController_, _$routeParams_) {
    $componentController = _$componentController_;
    $routeParams = _$routeParams_;
    $routeParams = {
      myId: 42
    }
  }));

  it('should init', function () {

    var ctrl = $componentController('myComponent', $routeParams, null);

    expect(ctrl.myId).toBe(42);

  });
});

但遗憾的是 ctrl.myId未定义,因为没有正确注入$ routeParams。为什么呢?

2 个答案:

答案 0 :(得分:1)

我和你的情况非常相似,谷歌搜索了一段时间但几乎找不到任何东西,但最后我自己解决了问题:这是你案件的解决方案:

describe("spec for myComponent", function () {

  var $componentController;
  var mockRouteParams = {id : 1};

  beforeEach(module('app'));

  beforeEach(inject(function (_$componentController_) {
    $componentController = _$componentController_;
  }));

  it('should init', function () {

    var ctrl = $componentController('myComponent', {$routeParams:mockRouteParams}, null);

    expect(ctrl.myId).toBe(1);

  });
});

同时检查Mocking $routeParams in a test in order to change its attributes dynamically有关$ routeParams的模拟。

答案 1 :(得分:1)

您似乎在这里重新定义struct Stack

$routeParams

执行以下操作可以解决您的问题(另请注意,您希望$routeParams = _$routeParams_; $routeParams = { myId: 42 } 属于id,而不是$routeParams):

myId