2016-09-16 53 views
1

我使用jasmine 2.3.
在此之後:http://tosbourn.com/using-loops-in-jasmine/我直接在「describe」嵌套函數放在一個FOR循環使用的茉莉花環(與注射服務)

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); 
     } 
    } 
    }); 
}); 

的問題是,外面的' it'功能,ProfileServiceundefined

+0

這意味着它不是injected.Check因果報應屏幕,並確保相應的文件包含在karma.config.js –

回答

1

由於需要ProfileService被注入,循環必須beforeEach塊後運行:如果你試圖像會發生什麼。

我可以看到兩個解決方案。或者:

使用硬編碼的配置文件列表並遍歷它們。而不是

for (var key in ProfileService.profile) { 

EG-做

for (var key in ['profile1', 'profile2'...) { 

或從外部文件加載配置文件。

OR

把for循環it測試的內部:

it('should set the object profile', function() { 
    for (var key in ProfileService.profile) { 
    if (ProfileService.profile.hasOwnProperty(key)) { 
     expect(ProfileService.profile[key]).toBeUndefined(); 
    } 
    } 
}); 
+0

我通常這樣做的方式是用硬編碼的值。無論如何,這是一個更好的測試。 –

+0

最有可能是更好的,但這取決於你在這裏測試的東西。 OP似乎在詢問如何測試'ProfileService',但可能是配置文件的加載超出了本單元測試的範圍。在這種情況下,使用ProfileService實例本身就非常好。 –

0

describe塊創建it塊,那麼beforeEach運行,那麼它會阻止,所以,是的,ProfileService不會當描述塊建立it塊,如果你在一個beforeEach定義它定義。但是,beforeEach不是唯一可以使用的地方inject

 
describe('method setProfile', 
    inject(
     function(ProfileService) { 
      //your code here 
     } 
    ) 
) 
+0

如果這有效,我會非常驚訝。原因是在這種情況下,注射器尚未創建。 –

+0

這是一個很好的觀點。 –