I am currently working on unit testing an Angular service with the following tools:
angular 1.3.8
angular-mocks 1.3.8
karma 0.13.19
jasmine 2.4.1
node 0.10.33
OS: Windows 7
Browser: PhantomJS 2.1.3
However, I am encountering an issue where the Angular service (MyService
) I intend to test is not being injected in the test file by the angular-mocks library (i.e., the 'inject' method does not work). Here is a snippet of my code:
main.js
(function() {
'use strict';
angular.module('module', [ 'ngCookies', 'ngSanitize' ]);
})();
service.js
(function () {
'use strict';
angular.module('module')
.factory('MyService', MyService);
MyService.$inject = ['Dependency'];
function MyService(Dependency) {
return {
method: method
};
function method() {
// do something
}
}
})();
service.spec.js
(function () {
'use strict';
describe('MyService', function () {
var deferred;
var MyService;
var DependencyMock = {};
beforeEach(module('module'));
beforeEach(module(function ($provide) {
$provide.value('Dependency', DependencyMock);
}));
beforeEach(inject(function (_MyService_, $q) {
MyService = _MyService_; // nothing is injected here
deferred = $q.defer(); // nothing is injected here
}));
it('should be injected', function () {
console.log(deferred); // logs 'undefined'
expect(MyService).toBeDefined(); // fails
});
describe('method', function () {
it('should have this method', function () {
expect(MyService.method).toBeDefined(); // fails as MyService is undefined
expect(typeof MyService.method).toBe('function');
});
});
});
})();
karma.conf.js
// list of files / patterns to load in the browser
files: [
'libs/angular/angular.js',
'libs/angular-mocks/angular-mocks.js',
'src/js/main.js',
'src/js/services/service.js',
'src/js/tests/unit/service.spec.js'
]
package.json
"devDependencies": {
"bower": "1.7.7",
"grunt": "0.4.5",
"grunt-contrib-clean": "0.7.0",
"grunt-contrib-concat": "0.5.1",
"grunt-contrib-connect": "0.11.2",
"grunt-contrib-copy": "0.8.2",
"grunt-contrib-cssmin": "0.14.0",
"grunt-contrib-jshint": "0.12.0",
"grunt-contrib-less": "1.1.0",
"grunt-contrib-uglify": "0.11.0",
"grunt-karma": "0.12.1",
"grunt-lesshint": "1.1.1",
"grunt-ngdocs": "0.2.9",
"grunt-processhtml": "0.3.9",
"jasmine-core": "2.4.1",
"karma": "0.13.19",
"karma-cli": "0.1.2",
"karma-coverage": "0.5.3",
"karma-jasmine": "0.3.6",
"karma-phantomjs-launcher": "1.0.0",
"karma-spec-reporter": "0.0.24",
"phantomjs-prebuilt": "2.1.3"
}
bower.json
"devDependencies": {
"angular": "1.3.8",
"angular-animate": "1.3.8",
"angular-cookies": "1.3.8",
"angular-mocks": "1.3.8",
"angular-soap": "2.1.1",
"bootstrap": "3.3.6",
"font-awesome": "4.5.0",
"angular-translate": "2.9.0",
"angular-sanitize": "1.3.8"
}
Upon investigation, it seems that the issue may be related to the use of angular-mocks
.