dimanche 1 février 2015

How to test a controller with a factory that needs to be resolved before the controller is loaded?

I need to test a controller that requires a factory to be resolved before the controller is loaded.


This is how the factory gets resolved in the routes:


app.js



angular
.module('c2gyoApp', [
...
])
.config(function($routeProvider) {
$routeProvider
...
.when('/sm', {
templateUrl: 'views/sm.html',
controller: 'SmCtrl',
resolve: {
stadtmobilRates: ['stadtMobilRates', function(stadtMobilRates) {
return stadtMobilRates().then(function(resp) {
return resp.data;
});
}]
}
})
...
otherwise({
redirectTo: '/c2g'
});
});


The factory:


stadtmobilrates.js



angular.module('c2gyoApp')
.factory('stadtMobilRates', function($http) {
var promise = null;

return function() {
if (promise) {
// If we've already asked for this data once,
// return the promise that already exists.
return promise;
} else {
promise = $http.get('stadtmobilRates.json');
return promise;
}
};
});


The declaration of the controller I need to test with the stadtmobilRates factory injected:


smcontroller.js



angular.module('c2gyoApp')
.controller('SmCtrl', [
'$scope',
'stadtmobilRates',
function($scope, stadtmobilRates) {
...
}
]);


My Karma test (generated by yeoman):


smcontrollertest.js



describe('Controller: SmCtrl', function() {

// load the controller's module
beforeEach(module('c2gyoApp'));

var SmCtrl;
var scope;

// Initialize the controller and a mock scope
beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new();
SmCtrl = $controller('SmCtrl', {
$scope: scope
});
}));

it('should calculate the correct price', function() {
expect(scope.price(10, 10, 0, 0, 'A', 'basic')
.toFixed(2)).toEqual((18.20).toFixed(2));
});

});


Of course this fails because the factory is not resolved:



PhantomJS 1.9.8 (Windows 7) Controller: SmCtrl should calculate the correct price FAILED
Error: [$injector:unpr] Unknown provider: stadtmobilRatesProvider <- stadtmobilRates <- SmCtrl


So how do I resolve and inject the factory before the tests starts? I found a lot of posts about mocking a service to test it, but nothing to resolve it before a test.


Aucun commentaire:

Enregistrer un commentaire