我正在尝试测试一个依赖于其他服务documentViewer的服务authService
angular
.module('someModule')
.service('documentViewer', DocumentViewer);
/* @ngInject */
function DocumentViewer($q, authService) {
// ...
this.view = function(doc) {
//...
}
}这就是我现在的测试
it('test', inject(function($q) {
var doc = {
view: function() {
return $q.resolve(0);
}
};
var auth = {
refreshProfileData: function() {
return $q.resolve(0);
},
};
var viewer = createViewer(auth);
}));
function createViewer(auth) {
var viewer;
module({
authService: auth
});
inject(function(documentViewer) {
viewer = documentViewer;
});
return viewer;
}问题是,我需要调用inject来获取$q,然后使用它创建模拟,向module注册模拟,然后再次调用inject来获取测试中的单元。
这会导致
错误:注射器已经创建,无法注册一个模块!在bower_components/angular-mocks/angular-mocks.js中(第2278行)
我在这里看到了很多答案,所以说您不能在module之后调用inject,但是它们不能提供任何替代上述场景的方法。
这里的正确方法是什么?
PS:我想避免使用beforeEach,我希望每个测试都是独立的.
发布于 2017-06-06 12:19:52
module用于定义哪些模块将加载inject,不能在inject之后调用,这是鸡蛋的情况。
module接受的对象用于定义模拟的服务$provide.value。
如果传递一个对象文字,每个键值对将通过$provide.value在模块上注册,键是字符串名称(或令牌),以与注入器上的值相关联。
像createViewer这样调用module和inject的函数最多只能有一个。如果这意味着这种自成一体的测试是反模式的,那就没有什么可以做的了。角度测试最适合于常见的习惯,包括beforeEach和局部变量。
为了消除对$q的依赖,可以将模拟的服务变成factory。
it('test', function () {
var authFactory = function ($q) {
return {
refreshProfileData: function() {
return $q.resolve(0);
},
};
};
// mocks defined first
module(function ($provide) {
$provide.factory('authService': authFactory);
});
var viewer;
inject(function(documentViewer) {
viewer = documentViewer;
});
// no module(...) is allowed after this point
var $q;
inject(function(_$q_) {
$q = _$q_;
});
var doc = {
view: function() {
return $q.resolve(0);
}
};
});https://stackoverflow.com/questions/44388419
复制相似问题