加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 如何在单元测试时在角度1.5中向$componentControll

发布时间:2020-12-17 07:15:11 所属栏目:安全 来源:网络整理
导读:我想在组件中向Controller添加依赖项: 这是我的组件: angular .module('app') .component('myComponent',{ template: 'divsome content/div',controller: ["$routeParams",function ($routeParams) { var ctrl = this; ctrl.myId = $routeParams.id; });
我想在组件中向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.为什么?

解决方法

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

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

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

  beforeEach(module('app'));

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

  it('should init',{$routeParams:mockRouteParams},null);

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

  });
});

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读