Reputation: 1074
I have service that looks like that:
angular.module('app').service('MyService' , function (dependency1, dependency2, dependency3 ...) {
function funcToTest() {
// Do something
}
}
How could I inject a specific dependency to the service? For example, I want to inject only dependency2
to my service and I don't care about the other dependencies.
Upvotes: 2
Views: 3059
Reputation: 7911
Unlike unit-testing Angular controllers, we have no way of directly passing dependencies. This is where $provide
service comes to rescue!
Here's a sample example:
beforeEach(module('myApp', function ($provide) {
mockDependecy2 = {
mockFunction: function() {}
};
$provide.value('dependency2', mockDependecy2);
}));
Then, you can write your specs normally:
beforeEach(inject(function(_MyService_, ...) {
...
MyService = _MyService_;
}));
describe("...", function() {
it("...", function() {
MyService.funcToTest();
// write expect statements here
})
})
As seen in the example, you can (optionally) enclose them with underscores which are ignored by the injector when the reference name is resolved.
Upvotes: 2
Reputation: 1703
This will automatically inject dependency2 in your service wherever it is used
var dependency2;
beforeEach(function () {
inject(function (dependency2){
dependency2 = dependency2;
});
}
Upvotes: 0