2014-06-21 45 views
3

我正在使用承諾異步加載模塊的框架。這些模塊包含我想爲其創建測試的方法(對於這個問題,可以假定它們是同步的)。如何在異步函數中包裝Mocha/Chai測試?

目前,我的代碼如下所示:

describe("StringHelper", function() { 
    describe("convertToCamelCase()", function() { 
     it("should convert snake-cased strings to camel-case", function(done) { 
      Am.Module.load("Util").then(function() { 
       var StringHelper = Am.Module.get("Util").StringHelper; 
       //Test here 
       done(); 
      }); 
     }); 
    }); 

    describe("convertToSnakeCase()", function() { 
     it("should convert camel-cased strings to snake case.", function(done) { 
      Am.Module.load("Util").then(function() { 
       var StringHelper = Am.Module.get("Util").StringHelper; 
       //Another test here 
       done(); 
      }); 
     }); 
    }); 
}); 

鑑於Am.Module.load()本質上是包裹在這樣的方式來回報承諾RequireJS通話,因此,應在開始時只加載一次,我如何重寫上述?

我基本上希望能有這樣的事情:

Am.Module.load("Util").then(function() { 
    var StringHelper = Am.Module.get("Util").StringHelper; 

    describe("StringHelper", function() { 
     describe("convertToCamelCase()", function() { 
      it("should convert snake-cased strings to camel-case", function(done) { 
       //Test here 
       done(); 
      }); 
     }); 

     describe("convertToSnakeCase()", function() { 
      it("should convert camel-cased strings to snake case.", function(done) { 
       //Another test here 
       done(); 
      }); 
     }); 
    }); 
}); 

不幸的是,上述不工作 - 測試根本不被執行。記者甚至不顯示describe("StringHelper")的部分。有趣的是,在玩過之後,這隻發生在全部這些測試都是以這種(第二代碼片段)方式編寫的。只要至少有一個以第一種格式寫入的測試,測試就會正確顯示。

+0

我有同樣的問題。 – chovy

回答

1

您可以使用Mocha的before()鉤子以異步方式加載Util模塊。

describe("StringHelper", function() { 
    var StringHandler; 

    before(function(done) { 
    Am.Module.load("Util").then(function() { 
     StringHelper = Am.Module.get("Util").StringHelper; 
     done(); 
    }); 
    }); 
    describe("convertToCamelCase()", function() { 
    it("should convert snake-cased strings to camel-case", function() { 
     //Test here 
    }); 
    }); 

    describe("convertToSnakeCase()", function() { 
    it("should convert camel-cased strings to snake case.", function() { 
     //Another test here 
    }); 
    }); 
}); 
+0

沒有想到多久前我發佈了這個答案,但感謝一堆! –

+0

我喜歡挖掘未解答的問題,以防萬一答案可能仍然有用。 :-)乾杯! – JME