【发布时间】:2016-07-28 08:40:14
【问题描述】:
我使用 Angular 1.5.5 和 Jasmine 作为测试框架。目前我必须做这样的事情才能通过测试:
function createController(bindings) {
return $componentController('myController', null, bindings);
}
beforeEach(inject(function (_$componentController_) {
$componentController = _$componentController_;
}));
describe('on pages updated', function () {
beforeEach(function () {
controller = createController({prop1: 0, prop2: 0});
controller.$onInit(); // you see I have to explitcitly call this $onInit function
});
it('should update isSelected and currentPage', function () {
expect(controller.prop1).toBe(0);
expect(controller.prop2).toBe(0);
controller.prop1= 1;
controller.prop2= 2;
controller.$onChanges(controller); // and $onChanges here as well
expect(controller.prop1).toBe(1);
expect(controller.prop2).toBe(2);
});
});
【问题讨论】:
-
你为什么要首先隐式触发它?
$onInit是安装组件时调用的生命周期钩子。$componentController没有理由在单元测试中单独调用该函数。除非您将组件作为一个整体进行测试,否则您绝对应该明确地触发这些事情。