[英]How can i inject a mock service into a unit test for a filter?
I have a simple angularjs filter (it takes an id and converts it to a name string), that depends on a custom service to do its work: 我有一个简单的angularjs过滤器(它需要一个id并将其转换为名称字符串),这取决于一个自定义服务来完成它的工作:
angular.module('app').filter('idToName',
function(User) {
return function(id) {
var result, user;
result = '';
if (id) {
result = 'no name found';
user = User.getById(id);
if (user) {
result = user.firstName;
}
}
return result;
};
}
);
and I want to write a unit test for it. 我想为它写一个单元测试。 I would like to be able to inject a mock of the User service into the test.
我希望能够在测试中注入用户服务的模拟。
I can do this for a controller unit test as shown in the documentation: 我可以为控制器单元测试执行此操作,如文档中所示:
var mockUserService;
mockUserService = {
getById: function(id) {
return {
firstName: 'Bob'
};
}
};
beforeEach(inject(function($rootScope, $controller) {
var ctrl, scope, userService;
userService = mockUserService;
scope = $rootScope.$new();
return ctrl = $controller('someController', {
$scope: scope,
User: userService
});
}));
but replacing $controller with $filter in the beforeEach does not work, as I presume filters are constructed differently by angular (ie don't allow you to inject locals as a second parameter to the constructor.) 但是在beforeEach中用$ filter替换$ controller是行不通的,因为我假设过滤器的构造方式与angular不同(即不允许你将locals作为第二个参数注入构造函数。)
Has anyone come across this / solved this before? 有没有人碰到这个/之前解决了这个问题?
Ok, figured this out thanks largely to this answer. 好的,这很好地归功于这个答案。
The trick was to simply override the factory provider of the service, by using angular-mocks.js model function in a before each (angular just takes the last defined factory it would seem) 诀窍是简单地覆盖服务的工厂提供者,在每个之前使用angular-mocks.js模型函数(angular只需要最后定义的工厂)
beforeEach(module(function($provide) {
$provide.factory('User', function() {
var getSync;
getById = function(id) {
return {
firstName: 'Bob'
};
};
return {
getById: getById
};
});
}));
I suspect that I'll need to be careful with teardown between tests, but the injection into the filter now works fine. 我怀疑在测试之间我需要小心拆卸,但注入过滤器现在可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.