Reputation: 80
This question is not about including a service to test or to provide a mock that replaces a service.
Situation:
The Factory I'd like to test is about parsing a set of properties and provide this information via getter functions. The following pseudocode describes what is happening right now (supprisingly it works, although it is quite hacky to create dynamically tests depending on the data length.)
...
describe('fancyTest', function() {
// 1
beforeEach(function() {
// 7
module('app');
inject(function($injector) {
// 8
Factory = $injector.get('app.ToTestFactory');
UtilService = $injector.get('app.Util'); // bad, as to late...
});
});
// 2
describe('dataTest', function() {
// 3
// Goal: data = UtilService.getData('dataset1');
data = [{id:'test1'}, {id:'test2'}];
for (i = 0, l = data.length; i < l; i += 1) {
test(data[i]);
}
function test(properties) {
// 4
describe('datatest #' + i, function() {
var elem;
// 5
beforeEach(function() {
// 9
elem = new Factory(properties)
});
// 6
it('should provide the correct id', function() {
// 10
expect(elem.id()).toBe(properties.id);
});
...
});
}
}
...
}
The UtilService.getData() is a simple method that reads the data out of some constants that are only injected when executing tests. It's maybe important, that I dont want to load them asynchronous.
Problem:
The Jasmine framework has a quite uninituitive workflow and first runs and initializes all describe blocks, before it runs through the beforeEach. The order is written in the comments.
Do I have no chance to inject the UtilService before the data-loop runs through?
Thanks for helping me out!
Upvotes: 0
Views: 1260
Reputation: 399
If your UtilService is a factory, you can inject the service into every test with the before each
beforeEach(function() {
module('app');
var UtilService;
inject(function(_UtilService_) {
UtilService = _UtilService_;
});
});
The way jasmine sets up tests, as long as you load all of your dependencies properly in your Karma Config, you shouldn't ever have to use $injector to pull in a service.
And because the underscores are probably a little confusing, angular will provide an underscored service so you can create a new instance every time.
Upvotes: 1