angularjs - 如何在单元测试 Angular 组件 Controller 中隐式触发 $onInit 或 $onChanges?

标签 angularjs unit-testing

我使用 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/

相关文章:

AngularJS 1.2 Animation 回退,当不支持 cssanimations 时

java - 从命令行进行 Junit 测试 无可运行方法异常

reactjs - 开 Jest : Cannot find module 'react' , 和其他 node_modules

php - 尝试在 Yii2 中运行 phpunit 时出现 Cygwin 问题

python - 启动一个 "throwaway"MySQL session 来测试代码?

javascript - 使用 uib-accordion 的条件标题颜色

javascript - 混合 $q 和 ES6 promise 时测试 Angular

python - Python单元测试在什么情况下运行失败?

javascript - Controller 中 AngularJS 范围的问题

javascript - 将参数传递给 AngularJS 模板内的函数