I have difficulties unit testing angularJS due to the injector not injecting properly. Anything I inject turns out to be undefined.
Module:
app.module.js
angular.module('myServices', []);
AngularTest.js
describe('AngularTest', function() {
beforeEach(module('myServices'));
var scope;
beforeEach(inject(function(_$rootScope_) {
// The injector unwraps the underscores (_) from around the parameter names when matching
scope = _$rootScope_;
}));
describe('Testing Angular injection', function() {
it('scope should be defined', function() {
expect(scope).toBeDefined(); // fails
});
});
});
I have successfully tested controllers in my main module, however, this particular module is testing my sanity.
Any ideas ?
Karma file:
files: [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-resource/angular-resource.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-animate/angular-animate.js',
'app/bower_components/angular-cookies/angular-cookies.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/app.module.js',
'app/components/**/controller/*.js',
'app/components/**/model/*.js',
'app/components/**/test/unit/*.js'
]
The service module is defined in app.module.js and the service is at app/components/services/model/myService.js (The path seems illogical, I tried to abstract my structure to generalize this question as much as possible)
Karma also seems to not complain: From the log:
28 08 2015 03:38:47.095:WARN [karma]: No captured browser, open http://localhost:9876/
28 08 2015 03:38:47.107:INFO [karma]: Karma v0.13.9 server started at http://localhost:9876/
28 08 2015 03:38:47.151:INFO [launcher]: Starting browser Safari
28 08 2015 03:38:54.790:INFO [Safari 8.0.6 (Mac OS X 10.10.3)]: Connected on socket jhi7nBcWAV_vCJkMAAAA with id 68159057
Followed by the failing test case:
Safari 8.0.6 (Mac OS X 10.10.3) AngularTest Testing Angular injection scope should be defined FAILED
/path/to/project/app/bower_components/angular/angular.js:68:32
forEach@/path/to/project/app/bower_components/angular/angular.js:336:24
loadModules@/path/to/project/app/bower_components/angular/angular.js:4369:12
createInjector@/path/to/project/app/bower_components/angular/angular.js:4294:22
workFn@/path/to/project/app/bower_components/angular-mocks/angular-mocks.js:2390:60
/path/to/project/app/bower_components/angular/angular.js:4408:30
Expected undefined to be defined.
/path/to/project/app/components/services/test/unit/AngularTest.js:16:34
Solution: Changed the browser to Chrome in the karma config file and the debug log spat out much more detailed information on what was wrong!
Turned out I did not include needed module dependencies in my karma files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With