我怎么上测试茉莉这个模块?问题是,这是非常困难的测试 $控制器
因为函数隐藏在闭包内,这是非常困难的测试。
how do I test this module on jasmine ?
The problem is that it's very difficult to test the $controller
because the function is hidden inside a closure, it’s very difficult to test them.
在换句话说,给定以下模块定义,写一个单元测试用于MainCtrl似乎是不可能的。
In other words, given the module definition below, writing a unit test for MainCtrl seems impossible.
(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.
}));
});
在角注入 _ $ _控制器
茉莉花测试功能里面的服务,控制器的实例创建返回一个未定义$范围。
When angular inject the _$controller_
service inside the jasmine test function, The instance of the controller created returns with an undefined $scope.
所以你怎么能测试它?
我在计算器上一个解决这个问题的搜索,没有给我,我一直在寻找让我实现了我自己的一个答案。
My search on StackOverflow for a solution to this problem, didn't give me the answer I was looking for so I implemented one of my own.
可以茉莉花简单地通过这样的测试:
It can be tested with jasmine simply by doing this :
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 它
希望它帮助!