2015-05-22 55 views
0

所以,我在我的node.js應用程序上運行一些測試。摩卡測試beforeEach內循環 - 異步問題

該測試遍歷我所有的模型並檢查每個模型的暴露api。 it調用僅檢查公共模型,具體取決於型號的public屬性。

在調用it之前,我想在每次迭代時使用beforeEach將一些測試數據傳遞給模型。不幸的是,由於異步調用(我猜測),beforeEach中的迭代器值保持不變。我猜這個循環是在beforeEach之前執行的。每個型號有兩個it調用,導致每個型號調用beforeEach兩次。


UPDATE

我想我必須表明我的整個使用情況下會引起這一點比我在這裏要求更復雜。科迪的解決方案似乎是可能的,但它仍然不能幫助我的用例。這是因爲我在循環中有一些條件,只對某些模型運行測試,而不是全部。此外,還有兩個it調用,這意味着beforeEach在循環的每次迭代中被調用兩次。下面的代碼:

var models = {'Ate': {'property1': 'prop'}, 'Bat': {'property2': 'prop2'}, 'Cat': {'property3': 'prop3'}}; 
var modelConfigs = {'Ate': {'public': 'true'}, 'Bat': {'public': 'false'}, 'Cat': {'public': 'true'}}; 

describe('Given an array of model objects', function(){ 

    for(var key in modelConfigs) { 

     var m = key; 
     var modelConfig = modelConfigs[m]; 
     var model = models[m].definition; 
     var modelPlural = models[m].settings.plural; 

     if(modelConfig.public) { // Condition runs for only some models  
      beforeEach(function (done) { 
       var test = this; 
       var testKey = m; 
       console.log(testKey); //Output is always Cat. 
       done(); 
      }); 

      lt.describe.whenCalledRemotely('GET', '/api/' + modelPlural, function() { 
       it('should have status code 200', function() { //First it call 
        assert.equal(this.res.statusCode, 200); 
       }); 
       it('should be sorted DESC by date', function() { //Second it call 
        var modelRes = this.res.body; 

        expect(modelRes).to.be.instanceOf(Array); 
        expect(modelRes).to.have.length.below(11); 
        console.log(modelRes.length); 

        if(modelRes.length > 0) { 
         for(var i=1; i< modelRes.length; i++) { 
          expect(modelRes[i-1]['date']).to.be.at.least(modelRes[i]['date']); 
         } 
        } 
       }); 
      });  
     } 
    } 
}); 
+0

是我們應該承擔app.models看起來像'[{「A」: 'a'},{'b':'b'},{'c':'c'}]'或者像'{'a':'a','b':'b','c': 'C'}'?因爲'{{'a':'a'},{'b':'b'},{'c':'c'}}'不是一個有效的JavaScript對象。除此之外,你的for語句有一個拼寫錯誤,應該閱讀'for(var key in models){'而不是。 –

+0

我匆匆輸入了這個內容,所以做了一些拼寫錯誤。我猜這個代碼只是代表性的。我現在做了編輯:) – KaushikTD

+0

沒問題,只要總是能夠幫助人們回答問題,就可以糾正這些小錯別字。我在下面發佈了一個「工作」解決方案,但它絕對不是世界上最乾淨的解決方案。它基本上將for循環分解爲before/beforeEach函數。 –

回答

0

下面的代碼工作,但我敢肯定有可用的清潔的解決方案:

var models = {'a': 'a', 'b':'b', 'c':'c'} 
var modelsArray = [] 
for(var key in models) { 
    modelsArray.push(key) 
} 
describe("Given models", function() { 
    var currModel, index, testKey, test 
    before(function() { 
    index = 0; 
    }) 
    beforeEach(function() { 
    test = this; 
    testKey = modelsArray[index] 
    currModel = models[testKey] 
    index++ 
    }) 
    for(var i = 0; i < modelsArray.length; i++) { 
    it("Does whatever you need to test", function() { 
     console.log(testKey) 
    }) 
    } 
}) 
+0

嘿科迪,請看看我的更新,也許這會讓你更好地瞭解我的問題實際上是什麼。您的解決方案適用於我所問的問題,但我的使用案例稍微複雜一些。相應地編輯了這個問題。謝謝! – KaushikTD