我正在开发一个应用程序,我需要在路由器(ngRoute)中解决 promise 。问题是我不确定如何为此编写单元测试,我将 karma 与 mocha 和 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);
});
});
此时我收到错误:
Unknown provider: newOrdersProvider <- newOrders
我明白为什么会出现此错误,但我不知道如何解决。基本上我不知道如何测试路由中解析的 promise 。
预先感谢您的帮助!
最佳答案
经过大量搜索和阅读AngularJS Testing Cookbook我找到了如何将 promise 的结果注入(inject) Controller 中。 主要代码没有改变,所以我在这里只发布单元测试的更新代码:
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);
});
});
如果有人有更好/不同的解决方案,我也想听听!
关于angularjs - 如何使用 karma 和 mocha+chai 单元测试 angularjs 路由的解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29940498/