我想用茉莉花的上下文,所以我可以組織我的嘲笑返回。這裏有一些僞代碼來演示我想要做什麼。我期待這兩個預期都能通過:使用茉莉花的上下文
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'.
我怎樣才能做到這一點?你看到我想用描述塊做什麼?
你爲什麼不這樣做'beforeEach(函數(ServiceData){ ServiceData.message = '我的消息兩個' });' – Chandermani
@Chandermani您將需要注入'()'以及 – james
您應該採取看看sinon嘲笑/ stubbing – james