How to inject angular value and angular constant into karma unit test?
Since you are adding the c2gyoApp
module with:
beforeEach(module('c2gyoApp'));
Everything registered inside that module should be injectable. So, this should work:
var smConfig, stadtmobilRates;
beforeEach(inject(function($controller, $rootScope, _smConfig_, _stadtmobilRates_) {
scope = $rootScope.$new();
DatetimepickerCtrl = $controller('DatetimepickerCtrl', {
$scope: scope
});
smConfig = _smConfig_;
stadtmobilRates = _stadtmobilRates_;
}
Related videos on Youtube
Comments
-
mles almost 2 years
I want to test this controller
/controllers/datetimepicker.js
angular.module('c2gyoApp') .value('smConfig', { rate: 'A', tariff: 'classic' }) .controller('DatetimepickerCtrl', [ '$scope', 'stadtmobilRates', 'smConfig', function($scope, stadtmobilRates, smConfig) { ... $scope.getCurrentRate = function(rate, tariff) { // studi and classic have the same rates if (tariff === 'studi') { tariff = 'classic'; } return stadtmobilRates[tariff][rate]; }; ... } ]);
I have changed the controller since I wrote the tests. Some constants have moved to
angular.module('c2gyoApp').value('smConfig'){}
and I also need the constant fromangular.module('c2gyoApp').constant('stadtmobilRates'){}
:/services/stadtmobilrates.js
angular.module('c2gyoApp') .constant('stadtmobilRates', { 'classic': { 'A': { 'night': 0, 'hour': 1.4, 'day': 21, 'week': 125, 'km000': 0.2, 'km101': 0.18, 'km701': 0.18 }, ... });
This is my test so far:
/test/spec/controllers/datetimepicker.js
describe('Controller: DatetimepickerCtrl', function() { // load the controller's module beforeEach(module('c2gyoApp')); var DatetimepickerCtrl; var scope; // Initialize the controller and a mock scope beforeEach(inject(function($controller, $rootScope) { scope = $rootScope.$new(); DatetimepickerCtrl = $controller('DatetimepickerCtrl', { $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)); ... }); });
How do I inject
angular.module('c2gyoApp').value('smConfig'){}
andangular.module('c2gyoApp').constant('stadtmobilRates'){}
into the test? I'm using the standard yeoman layout. The karma.conf file includes all necessary .js files, so it's just a question of where to inject the angular elements.