如何在 jasmine 上测试这个模块?
问题是测试起来非常困难$controller
因为函数隐藏在闭包内,所以测试它们非常困难。
换句话说,考虑到下面的模块定义,为 MainCtrl 编写单元测试似乎是不可能的。
(function () {
'use strict';
angular.module('app', []);
function MainCtrl() {
var mc = this;
mc.obj = {
val : 50
};
}
angular.module('app').controller('MainCtrl', MainCtrl);
} () );
和“典型”茉莉花测试
describe('app', function(){
beforeEach(module('app'));
it('should create an objet with val 50', inject(function(_$controller_) {
var scope = {},
ctrl = _$controller_('MainCtrl', {$scope:scope});
expect(scope.obj.val).toBe(50); // returns Expected undefined to be 50.
}));
});
当有角度注入时_$controller_
在 jasmine 测试函数内的服务中,创建的控制器实例返回未定义的 $scope。
那么如何测试呢?
我在 StackOverflow 上搜索此问题的解决方案,但没有给出我正在寻找的答案,因此我实现了自己的解决方案。
只需执行以下操作即可使用 jasmine 对其进行测试:
describe('app', function () {
var $controller;
beforeEach(function () {
module('app');
inject(function (_$controller_) {
$controller = _$controller_('MainCtrl');
});
});
//-- spec - test controller
describe('Controller : MainCtrl', function () {
it('should create an object with val 50', function () {
expect($controller.obj.val).toBe(50);
});
});
});
这是一个jsfiddle http://jsfiddle.net/jfabfab/g3a6hxmx/ for it
希望能帮助到你 !
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)