我使用 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);
});
});
最佳答案
github 上有一个与此相关的问题:https://github.com/angular/angular.js/issues/14129
基本上它按预期工作,不会自动调用 $onInit
或 $onChanges
。
it makes no sense (or low sense) to execute $onInit, I explain it: $componentController is to instance controllers a kind of replacement for $controller, but instead of creating instances of controllers registered by the controllerProvider it creates instances of controllers registered through directives (the ones that satisfies a component definition). So, once you have the instance of the controller, you can call manually $onInit, and all the lifecycle of your controller, the idea is that you are testing a controller, not a directive (and its relationships).
关于angularjs - 如何在单元测试 Angular 组件 Controller 中隐式触发 $onInit 或 $onChanges?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38631204/