我想使用 jasmine 的上下文,这样我就可以组织我的模拟返回的内容。这是一些伪代码来演示我想要做什么。我希望这两个期望都能通过:
describe('a module', function(){
var whatTheFunctionReturns;
beforeEach(function(){
module('anApp', function($provide){
$provide.value('aFactory', { aFunction: whatTheFunctionReturns })
}
});
describe('when the function returns alpha', function(){
whatTheFunctionReturns = 'alpha'
it('should get data from a service', function(){
expect(aFactory.aFunction).toEqual( 'alpha' )
});
});
describe('when the function returns beta', function(){
whatTheFunctionReturns = 'beta'
it('should get data from a service', function(){
expect(aFactory.aFunction).toEqual( 'beta' )
});
});
});
请仔细阅读以上内容。你明白我在做什么吗?编码
$provide.value('aFactory', { aFunction: whatTheFunctionReturns })
在 beforeEach 块中写入一次,但变量
whatTheFunctionReturns
在两个描述块中更改,when the function returns alpha
并且when the function returns beta
.
但是,它不起作用。这是一些真实的代码,我正在尝试测试控制器并模拟它所依赖的工厂:
describe('firstController', function(){
var $rootScope, $scope, $controller
var message = 'I am message default'
beforeEach(function(){
module('App',function($provide){
$provide.value('ServiceData', { message: message})
});
inject(function(_$rootScope_,_$controller_){
$rootScope = _$rootScope_
$scope = $rootScope.$new()
$controller = _$controller_
$controller('firstController', { '$rootScope' : $rootScope, '$scope' : $scope })
});
});
describe('when message 1', function(){
beforeEach(function(){
message = 'I am message one'
});
it('should get data from a service', function(){
expect($scope.serviceData.message).toEqual( '1' ) // using wrong data so I can see what data is being returned in the error message
});
});
describe('when message 2', function(){
beforeEach(function(){
message = 'I am message two'
});
it('should get data from a service', function(){
expect($scope.serviceData.message).toEqual( '2' ) // using wrong data so I can see what data is being returned in the error message
});
});
});
这是我收到的错误消息:
Firefox 34.0.0 (Ubuntu) firstController when message 1 should get data from a service FAILED
Expected 'I am message default' to equal '1'.
Firefox 34.0.0 (Ubuntu) firstController when message 2 should get data from a service FAILED
Expected 'I am message one' to equal '2'.
它工作了一半。变量正在更新,但仅在最后一个描述块 ( 'when message 2'
) 中。这是我期望返回的内容:
Firefox 34.0.0 (Ubuntu) firstController when message 1 should get data from a service FAILED
Expected 'I am message one' to equal '1'.
Firefox 34.0.0 (Ubuntu) firstController when message 2 should get data from a service FAILED
Expected 'I am message two' to equal '2'.
我怎样才能做到这一点?你看到我想用描述块做什么了吗?