Mocha --require 等到迁移

Mocha --require wait until migration

在开始我的 mocha 套件测试之前,我遇到了 运行 数据库迁移的挑战。

我正在使用标志 --require 来加载我创建的 bootstrap.js 模块以及 运行 数据库迁移。

问题是迁移是一个异步函数,正如您所知 returns 立即。那么,有什么方法可以等待模块准备好,直到一切都完成了吗?

我可以使用一些同步库将迁移转换为同步,但我想听听更多策略。

您可以定义一个全局 before 挂钩,如下所示:

import {runMigration} from './bootstrap';
before(done => {
    runMigration().then(done);
});

describe('some part of my suite', () => {
    /* ... */

如果您在 "root suite" 中编写此挂钩 - 也就是说,在您自己的任何 describe 块之外 - 它会 运行 在所有测试之前,无论您将其放在哪个文件中阻止。

Docs on root level hooks

请注意,您的挂钩花费的时间太长,您可能会开始收到类似 "Timeout of 2000ms exceeded" 的错误,这可以通过 运行ning mocha with --timeout 标志来解决 - 例如 mocha --timeout 10000