我正在开发一个框架,其中包含使用 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()
本质上是对 RequireJS 的调用,以返回 promise 的方式包装,因此,应该只在开始时加载一次,我怎么能重写上面的内容?
我基本上希望有这样的东西:
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")
的部分。有趣的是,经过尝试后,只有当所有 测试都以这种(第二个代码片段)方式编写时,才会发生这种情况。只要至少有一个以第一种格式编写的测试,这些测试就会正确显示。
最佳答案
您可以使用 Mocha 的 before()
Hook 异步加载 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
});
});
});
关于javascript - 如何在异步函数中包装 Mocha/Chai 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24343311/