【发布时间】:2015-01-16 05:50:02
【问题描述】:
我有一个依赖于服务的控制器,作为它初始化的一部分,它调用了服务上的一个函数。这是一个人为的例子:
describe('tests', function() {
var _scope, service, serviceValue = 'value';
beforeEach(module('app'));
beforeEach(inject(['$rootScope','$controller', function($rootScope, $controller) {
_scope = $rootScope.$new();
service = {
get: function(key) {
return serviceValue;
}
};
$controller('myController', {
'$scope': _scope,
'service': service
});
}]));
describe('initialisation', function() {
describe('key exists', function() {
it('should find the key', function() {
expect(_scope.message).toBe('found the key');
});
});
describe('key does not exist', function() {
beforeEach(function() {
serviceValue = undefined;
});
it('should not find the key', function() {
expect(_scope.message).toBe('did not find the key');
});
});
});
});
angular.module('app').controller('myController', ['$scope','service',
function($scope, service) {
if(service.get('key') === 'value') {
$scope.message = 'found the key';
} else {
$scope.message = 'did not find the key';
}
});
当 key 不存在时的测试失败,因为控制器初始化已经在第一个 beforeEach 中运行,在下一个 beforeEach 运行以更改服务返回值之前。
我可以通过在 beforeEach 的“密钥不存在”测试中重新创建整个控制器来解决这个问题,但这对我来说似乎是错误的,因为它为测试初始化了两次控制器。有没有办法让控制器初始化为每个测试运行,但在所有其他 beforeEach 函数运行之后。
这是初始化控制器的正确方法吗?我错过了茉莉花的一些功能吗?
【问题讨论】: