[英]how do I mock a dependency of a service in my angular unit test?
I'm using karma, angular and mocha. 我正在使用业力,角度和摩卡。
The MyServices
module I want to inject. 我要注入的MyServices
模块。 It's addThing
method also calls a $localStorage
provider and I want to test that the $localStorage.setItem
method has been implicitly called when I call MyServices.addThing(data)
它的addThing
方法也调用$localStorage
提供程序,我想测试在调用MyServices.addThing(data)
时隐式调用$localStorage.setItem
方法
Here's my code: 这是我的代码:
describe('MyServices', function() {
var $q;
var $rootScope;
var $scope;
var MyServices;
var $timeout;
var $httpBackend;
// inject modules
beforeEach(function(){
module('my.stuff');
var _LocalStorage_ = {
setItem: function(){
return 'foo';
}
};
// mock the dependencies of the module we are testing
module(function ($provide) {
$provide.value('$localStorage', _LocalStorage_); //here is where the error occurs
});
});
beforeEach(inject(function (_$q_, _$rootScope_, _$timeout_, _MyServices_, _$httpBackend_) {
$q = _$q_;
$rootScope = _$rootScope_;
$timeout = _$timeout_;
MyServices = _MyServices_;
$httpBackend = _$httpBackend_;
$scope = $rootScope.$new();
}));
it.only('should call a method and access localStorage', function(){
var spyAdd = sinon.spy(MyServices, 'addThing');
var spySetItem = sinon.spy($localStorage, 'setItem');
MyServices.addThing({ name: 'Thing' });
expect(spyAdd.callCount).to.equal(1);
expect(spySetItem.callCount).to.equal(1);
})
});
When I run it I get an error that $localStorage
is undefined. 当我运行它时,我收到$localStorage
未定义的错误。
you don't have register that fake $localStorage, just use the original one and create a spy on the setItem method. 你没有注册假$ localStorage,只需使用原来的并在setItem方法上创建一个间谍。
so remove this 所以删除它
var _LocalStorage_ = {
setItem: function(){
return 'foo';
}
};
module(function ($provide) {
$provide.value('$localStorage', _LocalStorage_); //here is where the error occurs
});
but inject it here 但是把它注入这里
var $localStorage;
beforeEach(inject(function (_$q_, _$rootScope_, _$timeout_, _MyServices_, _$httpBackend_, _$localStorage_) {
$q = _$q_;
$rootScope = _$rootScope_;
$timeout = _$timeout_;
MyServices = _MyServices_;
$httpBackend = _$httpBackend_;
$scope = $rootScope.$new();
$localStorage = _$localStorage_; //here
}));
since you have already created a spy on the method, so nothing needs to be changed in the test. 因为你已经在方法上创建了一个间谍,所以在测试中不需要改变任何东西。
Try to declare LocalStorage outside of your beforeEach. 尝试在beforeEach之外声明LocalStorage 。 Btw, you don't need the _, you can just call it LocalStorage. 顺便说一句,你不需要_,你可以称之为LocalStorage。
I also recommend downloading SinonJS because it has a bunch of useful methods when spying or mocking dependencies. 我还建议下载SinonJS,因为它在间谍或模拟依赖项时有很多有用的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.