问题
I'm using jasmine 2.3.
Following this: http://tosbourn.com/using-loops-in-jasmine/ I placed a FOR loop directly in the 'describe
' nested function
describe('service Profile', function() {
var ProfileService;
beforeEach(function() {
module('app.services.profile');
inject(function(_ProfileService_) {
ProfileService = _ProfileService_;
});
});
describe('method setProfile', function() {
function setProfileTest(key) {
it('should set the object profile', function() {
expect(ProfileService.profile[key]).toBeUndefined();
});
}
for (var key in ProfileService.profile) {
if (ProfileService.profile.hasOwnProperty(key)) {
setProfileTest(key);
}
}
});
});
The problem is that outside the 'it
' function, ProfileService
still undefined
.
回答1:
Since you need ProfileService
to be injected, the loop must run after the beforeEach
block.
I can see two solutions. Either:
Use a hard-coded list of profiles and iterate through them. Eg- instead of
for (var key in ProfileService.profile) {
do
for (var key in ['profile1', 'profile2'...) {
or load the profiles from an external file.
OR
Put the for loop inside of the it
test:
it('should set the object profile', function() {
for (var key in ProfileService.profile) {
if (ProfileService.profile.hasOwnProperty(key)) {
expect(ProfileService.profile[key]).toBeUndefined();
}
}
});
回答2:
The describe
block creates the it
blocks, then the beforeEach
runs, then the it blocks, so, yes, ProfileService
won't be defined when the describe block is setting up the it
blocks if you define it in a beforeEach
. However, beforeEach
is not the only place you can use inject
. What happens if you try something like:
describe('method setProfile', inject( function(ProfileService) { //your code here } ) )
来源:https://stackoverflow.com/questions/39534436/using-loops-in-jasmine-with-injected-service