Reputation: 29186
I'm trying to unit test an Angular service, using Jamsine, and I'm stuck on how to inject the dependency for that service.
Here is my app.js
file, trimmed down to the essentials:
"use strict";
angular.module("myApp", []);
(function (app) {
app.factory("taskService", function ($http) {
return {
loadTasks: function (callback) {
}
};
});
app.controller("AppController", function ($scope, $http, taskService) {
});
} (angular.module("myApp")));
Here is the Jasmine test, again stripped down to the essentials:
describe("taskService tests", function () {
var svc = {};
beforeEach(function () {
angular.module("myApp");
// I also tried this, but not luck there either
// angular.module("myApp", ['taskService']);
inject(function (taskService) { // Fails to inject the service.
svc = taskService;
});
});
});
When running the tests, I get the error that inject
could not resolve the dependency for taskService
:
http://docs.angularjs.org/error/$injector:unpr?p0=taskServiceProvider%20%3C-%20taskService
I'm stuck on what to do here. When running the app itself, the service is injected no problem e.g.
app.controller("AppController", function ($scope, $http, taskService) {
but I'm not sure how to manually do the injection in the test.
Upvotes: 1
Views: 1407
Reputation: 12018
The problem is that you need to load your module myApp
using angular.mocks
not plain angular. It is the same as injecting stuff, you can't use plain angular, you need angular.mocks
's inject()
So just changing:
angular.module("myApp");
for:
module("myApp");
or:
angular.mock.module("myApp");
Notice that module()
is just a shorthand of angular.mock.module()
Cheers.
Upvotes: 7