【问题标题】:Angular 1.5 component unit testing with webpack使用 webpack 进行 Angular 1.5 组件单元测试
【发布时间】:2016-10-07 06:40:48
【问题描述】:

我正在尝试使用带有一些绑定的控制器测试组件:

class AppSpecificController {
  constructor() {
    this.text = this.initialText ? this.initialText : 'No initial text has been specified.';
  }
}

export const AppSpecificComponent = {
  bindings: {
    'initialText': '<bindInitialText'
  },
  templateUrl: '/app/components/app-specific/app-specific.html',
  controller: AppSpecificController,
  controllerAs: 'appSpecific'
};

export default AppSpecificComponent;

在我的单元测试文件中,我不想加载完整的应用程序,只加载我需要的东西。所以我想模拟一个模块,或者只是用模拟创建一个名为 something 的新模块,将组件添加到该模块,然后加载该模块:

import {AppSpecificComponent} from './app-specific.component';

describe('AppSpecificComponent', () => {
    let controller;
    let scope;
    let $componentController;

    beforeEach(() => {
      angular.module('mock-module', [])
        .component('appSpecific', AppSpecificComponent);

      // this fails
      module('mock-module');

      inject((_$componentController_, $rootScope) => {
        scope = $rootScope.$new();
        $componentController = _$componentController_;
      });

      controller = $componentController('appSpecific', {$scope: scope}, {initialText: 'Some text'});
    });

    it('should test something', () => {
      expect(true).toBeTruthy();
    });
});

创建模块 mock-module 很好,但加载它失败,显然在 not-so-much-loaded-module 中注入东西失败,以及创建一个我可以开始测试的控制器。如果能够独立于运行它的应用程序单独测试组件,那就太好了。

仅对 AppSpecificController 类使用 new 运算符是行不通的,因为您从组件接收到的绑定不存在:

// fails, no bindings available in controller
controller = new AppSpecificController();

【问题讨论】:

  • 嗨,克里斯,你解决了这个问题吗?
  • 啊,是的,我会添加一个答案。

标签: angularjs unit-testing jasmine webpack ngmock


【解决方案1】:

我在 StackOverflow 的其他地方找到了答案,但现在不知道在哪里了。但是我一直在寻找答案:

angular.mock.module($provide => {
  $provide.controller('SomeController', () => { ... });
  $provide.constant('someConstant', 'some constant');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-23
    • 2017-01-09
    • 2017-09-15
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 2019-01-02
    相关资源
    最近更新 更多