Reputation: 6422
I have created an app with yeoman
yo angular --minsafe
And I want to test a factory/service I created
yo angular:factory analyticsService
Which produces /app/scripts/services/analyticsService.js
'use strict';
angular.module('angularPlaygroundApp')
.factory('analyticsService', function ($resource) {
// Service logic
// ...
var meaningOfLife = 42;
// Public API here
return {
someMethod: function () {
return meaningOfLife;
}
};
});
and the test /test/spec/services/analyticsService.js
'use strict';
describe('Service: Analyticsservice', function () {
// load the service's module
beforeEach(module('angularPlaygroundApp'));
// instantiate service
var Analyticsservice;
beforeEach(inject(function (_Analyticsservice_) {
Analyticsservice = _Analyticsservice_;
}));
it('should do something', function () {
expect(!!Analyticsservice).toBe(true);
});
});
running grunt test produces the following failed test for the service
Running "karma:unit" (karma) task INFO [karma]: Karma v0.10.8 server
started at http://localhost:8080
/ INFO [launcher]: Starting browser Chrome WARN [watcher]: Pattern "/Users/lsims/projects/angular-playground/test/mock/*/.js" does not match any file. INFO [Chrome 31.0.1650 (Mac OS X 10.9.0)]: Connected on socket MTgYIXPHDT3JCSNU0ww9 Chrome 31.0.1650 (Mac OS X 10.9.0) Service: Analyticsservice should do something FAILED Error: [$injector:unpr] Unknown provider: AnalyticsserviceProvider <- Analyticsservice
My question is how does one test factories/services in Angular, and more specifically, how can one test the services and/or factories that Yeoman generates?
Thanks in advance
Upvotes: 3
Views: 990
Reputation: 67296
They are tested pretty much exactly as you have described. However, JavaScript is case sensitive, and you have changed the case of what the injector is going to search for.
analyticsService != Analyticsservice
The _Analyticsservice_
syntax allows you the wrap the literal value of your service in underscores so that you can then name the local variable to the same thing. So, asking inject
for _Analyticsservice_
is asking for a service named with the string "Analyticsservice"
. When you have defined a service with the name "analyticsService"
.
So, I think you want:
'use strict';
describe('Service: analyticsService', function () {
// load the service's module
beforeEach(module('angularPlaygroundApp'));
// instantiate service
var analyticsService;
beforeEach(inject(function (_analyticsService_) {
analyticsService = _analyticsService_;
}));
it('should do something', function () {
expect(!!analyticsService).toBe(true);
});
injector
in angular always appends the name Provider
to the end of the objects in manages. The the error is telling you that the injector could not find an object with the name "AnalyticsserviceProvider"
defined.
Upvotes: 4