How to unit test angularjs route's resolve with karma and mocha+chai? -
i working on app need resolve promises in router (ngroute). problem not sure how write unit tests this, using karma mocha , chai.
here part of code i'd test:
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(); } };
this how started write unit tests when didn't have resolve part yet:
describe('ordercontroller', function() { 'use strict'; var controller, service, httpbackend; beforeeach(module('myapp.orders')); beforeeach(inject(function($controller, _orderservice_, $httpbackend) { service = _orderservice_; httpbackend = $httpbackend; // create controller controller = $controller('ordercontroller', {}); })); beforeeach(function() { httpbackend.when('get', 'url/to/get/orders') .respond(200, {[...]}); }); aftereach(function() { httpbackend.verifynooutstandingexpectation(); httpbackend.verifynooutstandingrequest(); }); it('should list of new orders', function() { httpbackend.flush(); expect(controller.neworders).not.to.undefined; expect(controller.neworders.length).to.equal(3); }); });
at point getting error:
unknown provider: newordersprovider <- neworders
i understand why error, don't know how solve it. don't know how test promise resolves in route.
thanks in advance help!
after lot of searching , reading angularjs testing cookbook find out how inject result of promise in controller. main code doesn't change, post here update code unit tests:
describe('ordercontroller', function() { 'use strict'; var controller, service, httpbackend; // here inject 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 controller controller = $controller('ordercontroller', { // add them controller neworders: resolver.neworders(service) }); })); beforeeach(function() { httpbackend.when('get', 'url/to/get/orders') .respond(200, {[...]}); }); aftereach(function() { httpbackend.verifynooutstandingexpectation(); httpbackend.verifynooutstandingrequest(); }); it('should list of new orders', function() { httpbackend.flush(); expect(controller.neworders).not.to.undefined; expect(controller.neworders.length).to.equal(3); }); });
if has better/different solution i'd hear well!
Comments
Post a Comment