如何在单元测试Angular组件控制器中隐式触发$ onInit或$ onChanges? [英] How to trigger $onInit or $onChanges implictly in unit testing Angular component controller?

查看:69
本文介绍了如何在单元测试Angular组件控制器中隐式触发$ onInit或$ onChanges?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 1.5.5和Jasmine作为测试框架.目前,我必须做这样的事情,才能使测试通过:

I'm using Angular 1.5.5 and Jasmine as test framework. Currently I have to do something like this so that the test passes:

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

There is an issue in github regarding this: https://github.com/angular/angular.js/issues/14129

基本上它可以按预期运行,不会自动调用$onInit$onChanges.

Basically it is working as intended, not calling $onInit or $onChanges automatically.

执行$ onInit没有任何意义(或低级),我向它解释:$ componentController是实例控制器的一种替代品$ controller,但不是创建由controllerProvider注册的控制器的实例,而是创建$ insert的实例.通过指令(满足组件定义的指令)注册的控制器.因此,一旦有了控制器的实例,就可以手动调用$ onInit以及控制器的所有生命周期,其想法是要测试控制器,而不是指令(及其关系).

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).

这篇关于如何在单元测试Angular组件控制器中隐式触发$ onInit或$ onChanges?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆