Angular Jasmine UI 路由器将解析值注入测试 [英] Angular Jasmine UI router inject resolve value into test
问题描述
在我的 Angular 应用中,UI 路由器将承诺解析到控制器中.在尝试测试此控制器时,Karma 抱怨提供者未知.如何在测试中注入一个假对象来表示这个解析对象.
In my Angular app, UI router resolves a promise into the controller. When trying to test this controller, Karma is complaining about an unknown provider. How do I inject a fake object into the test to represent this resolve object.
我的应用程序代码如下所示:
My app's code looks something like:
angular.module('myapp')
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('tab.name', {
...
resolve: {
allTemplates: function(Templates) {
return Templates.all().then(function(templates) {
return templates;
});
}
}
})
})
.controller('QueriesCtrl', function(allTemplates, UserQuery) {
var vm = this;
vm.queries = allTemplates;
vm.goToUrl = function(index, data) {
var processedUrl = UserQuery.process(data, vm.queryTyped[index]);
UserQuery.goToUrl(processedUrl);
};
});
尝试运行测试时出现错误
When trying to run tests I get the error
Unknown provider: allTemplatesProvider <- allTemplates <- QueriesCtrl
我尝试创建一个间谍并注入它,但这不起作用.这是我目前的测试:
I've tried creating a spy and injecting it, but this does not work. Here's my test at the moment:
describe('Unit: queriesCtrl', function() {
var controller,
scope,
UserQuery;
beforeEach(function() {
module('myapp');
inject(function($injector) {
UserQuery = $injector.get('UserQuery');
allTemplates = jasmine.createSpyObj('allTemplates', [{a:1}, {a:2}, {b:3}]);
});
});
describe('goToUrl', function() {
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
controller = $controller('QueriesCtrl as ctrl', {
'$scope': scope
});
}));
it('should call UserQuery.process()', function() {
spyOn(UserQuery, 'process');
scope.ctrl.goToUrl();
expect(UserQuery.process).toHaveBeenCalled();
});
});
});
推荐答案
由于单元测试中不涉及路由,因此您必须使用 $controller 将
函数.你可以试试吗:allTemplates
作为普通对象注入
Since there is no route involved in unit test you would have to inject the allTemplates
as a normal object with $controller
function. Can you try:
controller = $controller('QueriesCtrl as ctrl', {
'$scope': scope,
'allTemplates':allTemplates
});
否则您可以使用 $provide
API 来创建虚拟服务.
Else you can use the $provide
API to create a dummy service.
module(function ($provide) {
$provide.value("allTemplates", {[{a:1}, {a:2}, {b:3}]});
在 beforEach
块中做第一件事.
Do it first thing in your beforEach
block.
这篇关于Angular Jasmine UI 路由器将解析值注入测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!