AngularJS和PouchDB服务的单元测试 [英] Unit Testing AngularJS and PouchDB Service
问题描述
我正在尝试对单个Angular工厂进行单元测试,但是很难正确地模拟和注入PouchDB对象.我的工厂代码当前如下:
I am attempting to unit test my individual Angular factories but am having a hard time trying to correctly mock and inject the PouchDB object. My factory code is currently as follows:
factory('Track', [function() {
var db = new PouchDB('tracks');
var resource = {
getAll: function() {
return db.allDocs({include_docs: true});
}
return resource;
}]);
我曾经尝试使用Angular的$ provide服务注入一个没有运气的模拟PouchDB实例:
I had tried to use Angular's $provide service to inject a mock PouchDB instance with no luck:
module(function($provide) {
$provide.value('PouchDB', {
allDocs: function() {
return 'MOCKED';
}
});
我不确定从这儿去哪里.任何帮助将不胜感激!
I am not entirely sure where to go from here. Any help would be greatly appreciated!
推荐答案
如评论中所述:
您必须将全局变量PouchDB
包装在服务中以使其可注入.这是由于Angular通过简单的函数参数执行DI.因此,只需执行以下操作即可:
As just stated in the comments:
you have to wrap the global variable PouchDB
inside a service to make it injectable. This is due to Angular doing DI via simple function-parameters. So just do something like:
angular.module('myModule')
.factory('PouchDBWrapper', function(){
return PouchDB;
}
然后您可以将其注入Track工厂:
Then you can inject it into your Track factory:
factory('Track', [function(PouchDBWrapper) {
var db = new PouchDBWrapper('tracks');
var resource = {
getAll: function() {
return db.allDocs({include_docs: true});
}
return resource;
}]);
在测试中,您可以通过以下方式对其进行模拟:
and in your test you can mock it by:
module(function($provide) {
$provide.factory('PouchDBWrapper', {
allDocs: function() {
return 'MOCKED';
}
});
这篇关于AngularJS和PouchDB服务的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!