2016-09-22 64 views
4

我有一个场景,我初始化控制器中的一些变量$ onInit方法。我如何测试这些属性是否设置正确?

控制器

ctrl.$onInit = function() { 
    ctrl.devices = _.cloneDeep(ctrl.formDevices); 
}; 

单元测试

it('should expose device related properties to view', function() { 
     expect(controller.devices).toBeDefined(); 
}; 

输出

Unit test output

回答

3

你必须明确地调用$的OnInit功能。 $ componentController不会调用这个函数,因为它是生命周期钩子的一部分,它不会运行。

$ onInit可以被称为隐含性,其可以被发现为here

检查$ onInit函数是否正确设置属性的最简单方法是调用$ onInit。毕竟,你正在测试$ onInit函数是否能够工作,而不是AngularJS是否经历了它的生命周期钩子。

it('should expose device related properties to view', function() { 
    controller.$onInit(); 
    expect(controller.devices).toBeDefined(); 
};