簡體   English   中英

如何在異步函數中包裝Mocha / Chai測試?

[英]How do I wrap Mocha/Chai tests within asynchronous functions?

我正在使用使用promises異步加載的模塊的框架。 這些模塊包含我想為其創建測試的方法(對於這個問題,可以假設它是同步的)。

目前,我的代碼類似於以下內容:

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()本質上是以一種返回promise的方式調用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")部分describe("StringHelper") 有趣的是,在玩完之后,只有在所有測試都以這種(第二個代碼片段)方式編寫時才會出現這種情況。 只要至少有一個以第一種格式編寫的測試,測試就會正確顯示。

您可以使用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
    });
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM