我正在开发一个应用程序,我需要在路由器中解析promises(ngRoute)。问题是我不知道如何为此编写单元测试,我使用的是kocha和chai。
以下是我要测试的代码部分:
function config ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/orders.html',
controller: 'OrderController',
controllerAs: 'vmr',
resolve: OrderController.resolve,
data: {...}
});
}
function OrderController (OrderService, newOrders) {
this.newOrders = newOrders;
}
OrderController.resolve = {
newOrders: function (OrderService) {
return OrderService.getOrders();
}
};
当我没有解决部分时,这就是我开始编写单元测试的方法:
describe('OrderController', function() {
'use strict';
var controller,
service,
httpBackend;
beforeEach(module('myApp.orders'));
beforeEach(inject(function($controller, _OrderService_, $httpBackend) {
service = _OrderService_;
httpBackend = $httpBackend;
// Create the controller
controller = $controller('OrderController', {});
}));
beforeEach(function() {
httpBackend.when('GET', 'url/to/get/orders')
.respond(200, {[...]});
});
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it('should get the list of new orders', function() {
httpBackend.flush();
expect(controller.neworders).not.to.undefined;
expect(controller.neworders.length).to.equal(3);
});
});
此时是我收到错误的地方:
未知提供商:newOrdersProvider< - newOrders
我明白为什么会收到此错误,但我不知道如何解决。基本上我不知道如何测试在路线中解决的承诺。
提前感谢您的帮助!
答案 0 :(得分:4)
经过大量搜索和阅读AngularJS Testing Cookbook后,我发现如何在控制器中注入promise的结果。 主要代码没有变化,所以我在这里只发布单元测试的更新代码:
describe('OrderController', function() {
'use strict';
var controller,
service,
httpBackend;
// here is where I will inject a new value
beforeEach(function() {
module('myApp.orders', function($provide) {
$provide.value('resolver', {
newOrders: function(service) {
return service.getOrders();
}
});
});
});
beforeEach(inject(function($controller, _OrderService_, $httpBackend, resolver) {
service = _OrderService_;
httpBackend = $httpBackend;
// Create the controller
controller = $controller('OrderController', {
// add them to the controller
newOrders: resolver.newOrders(service)
});
}));
beforeEach(function() {
httpBackend.when('GET', 'url/to/get/orders')
.respond(200, {[...]});
});
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it('should get the list of new orders', function() {
httpBackend.flush();
expect(controller.neworders).not.to.undefined;
expect(controller.neworders.length).to.equal(3);
});
});
如果某人有更好/不同的解决方案,我也希望听到它!