I have developed a Karma-Mocha test that involves injecting an AngularJS service.
Service Code:
(function() {
'use strict';
angular.module('portal').service(
'AmountFormatService',
function() {
return {
format : function(amount) {
if (amount != null) {
var isNegative = false;
if (amount.substring(0, 1) == '('
|| amount.substring(0, 1) == '-'
|| amount.substring(1, 2) == '-'
|| amount.substring(1, 2) == '(') {
isNegative = true;
}
amount = amount.replace(/[^0-9.]/g, '');
if (isNegative) {
amount = '-' + amount;
}
}
if (amount == '')
amount = null;
return amount;
}
}
});
})();
Karma Test:
describe('AmountFormatService', function () {
var amountFormatService;
beforeEach(function(){
angular.mock.module('portal', function(){
});
inject(function(_AmountFormatService_){
amountFormatService = _AmountFormatService_;
});
});
it('does something', function(){
//Expect this to do something
console.log(amountFormatService.format(23));
});
});
karma.conf.js (karma config file):
module.exports = function (config) {config.set({
frameworks: ['mocha', 'chai'],
files: [
'../../../node_modules/angular/angular.js',
'../../../node_modules/angular-mocks/angular-mocks.js',
'../../main/webapp/app.js',
'../../main/webapp/services/*.js',
'../../test/testAmountFormatService2.specs.js',
'../../main/webapp/services/AmountFormatService.js'
],
// coverage reporter generates coverage
reporters: ['progress', 'coverage'],
preprocessors: {
// source files for coverage
'../../main/webapp/services/*.js': ['coverage']
},
coverageReporter: {
dir : '../../../target/JSCodeCoverage/',
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'cobertura', subdir: '.', file: 'cobertura.txt' }
]
},
browsers: ['Firefox', 'IE'],
autoWatch: true,
plugins: [
'karma-firefox-launcher',
'karma-ie-launcher',
'karma-junit-reporter',
'karma-mocha',
'karma-chai',
'karma-coverage'
]
})
}
Encountering an error when running the test:
Error: [$injector:unpr] Unknown provider: AmountFormatServiceProvider <- AmountFormatService
http://errors.angularjs.org/1.6.4/$injector/unpr?p0=AmountFormatServiceProvider%20%3C-%20AmountFormatService
// AngularJS error details follow...
If anyone can provide insight into the issue, it would be greatly appreciated.