我正在尝试使用带有一些绑定的控制器测试组件:
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();