javascript - 如何在异步函数中包装 Mocha/Chai 测试?

标签 javascript mocha.js chai

我正在开发一个框架,其中包含使用 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/

相关文章:

javascript - 将 setTimeout 设置为变量有什么用以及是否需要clearTimeout

javascript - 如何在单元测试运行中初始化全局变量?

javascript - 重新布线和导入其他模块

reactjs - Jest stub 方法

javascript - 在 Mocha 测试中找不到 Chai 导出

javascript - jQuery 查找文本并隐藏该文本

javascript - 这些事件处理程序中的哪一个应该在窗口关闭时触发自定义函数?

javascript - (ASP.NET) args.IsValid 如何阻止表单被提交?

node.js - 如何使用mocha、node和selenium集成测试react-select多选下拉菜单?

node.js - 如何在 mocha 测试用例中暂停或等待——setTimeout 不起作用