mercredi 29 avril 2015

How to unit test angularjs route's resolve with karma and mocha+chai?

I am working on an app where I need to resolve promises in the router (ngRoute). The problem is that I am not sure how to write the unit tests for this, I am using karma with mocha and chai.

Here is the part of the code I'd like to 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 is how I started to write my unit tests when I didn't have the 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 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();
        console.log(route);
        expect(controller.neworders).not.to.undefined;
        expect(controller.neworders.length).to.equal(3);
    });
});

At this point is where I am getting the error:

Unknown provider: newOrdersProvider <- newOrders

I understand why I get this error, but I don't know how to solve it. Basically I don't know how to test the promise that resolves in the route.

Thanks in advance for your help!

Aucun commentaire:

Enregistrer un commentaire