【发布时间】:2015-01-02 04:42:35
【问题描述】:
我想在 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'.
我怎样才能做到这一点?你看到我想用描述块做什么了吗?
【问题讨论】:
-
你为什么不这样做
beforeEach(function(ServiceData){ ServiceData.message = 'I am message two' }); -
@Chandermani 你还需要
inject() -
你应该看看 sinon 的 mocking/stubbing
-
没错@james,我忘了那部分。
-
@james 我看了一下 sinon...那我可以使用上下文吗?
标签: angularjs jasmine angular-mock