2014-06-21 47 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