【问题标题】:In MochaJS: How to run asynchronous tests sequentially?在 MochaJS 中:如何按顺序运行异步测试?
【发布时间】:2023-03-08 20:38:01
【问题描述】:

我正在使用 MochaJS 框架对 NodeJS 代码进行单元测试。

测试如下所示:

import 'mocha';
import { assert } from 'chai';
import { describe } from 'mocha';

describe('Test Suite', () => {
    function execute(testData: string) {
        it('Individual Test', async function() {
            // await some asynchronous call using testData
            // do some asserts
        });
    }

    const testData: string[] = ["test 1", "test 2", "test 3"];

    for (const data: string of testData) {
        execute(data);
    }
});

事实证明,多个测试(名为“单独测试”)将并行运行。有什么方法可以等待每个测试,以便在下一个测试开始之前完成?我不想为每个 testData 项目声明单独的测试,因为这将是大量的复制/粘贴。

【问题讨论】:

  • 如果你在没有包装函数的情况下编写测试,它们会起作用吗?
  • 你怎么知道它是并行运行的

标签: node.js mocha.js chai


【解决方案1】:

确保不要使用 mocha 的 --parallel 标志。

你有两个选择。在个人测试的异步函数中使用等待。

或者您可以使用 delete "async" 并使用 done() 进行异步测试。当测试应该结束时调用 done()。如果您调用它时出错,则测试将失败。确保只调用 done() 一次。

it('Individual Test', function(done) {
    aPromise().then(v => {
      done();
    }).catch(done);
});

参考资料: 完成:https://mochajs.org/#asynchronous-code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 2015-12-21
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    相关资源
    最近更新 更多