运行 ava test.before() 所有测试仅一次

Run ava test.before() just once for all tests

我想使用 test.before() 来 bootstrap 我的测试。我试过的设置不起作用:

// bootstrap.js
const test = require('ava')

test.before(t => {
  // do this exactly once for all tests
})


module.exports = { test }


// test1.js

const { test } = require('../bootstrap')

test(t => { ... {)

AVA 会在每个测试文件前运行 before() 函数。我可以在 before 调用中进行检查以检查它是否已被调用,但我想找到一个更干净的过程。我尝试将 require 参数与:

一起使用
"ava": {
  "require": [
    "./test/run.js"
  ]
 }

有:

// bootstrap,js
const test = require('ava')

module.exports = { test }


// run.js

const { test } = require('./bootstrap')

test.before(t => { })


// test1.js
const { test } = require('../bootstrap')

test(t => { ... {)

但这与 worker.setRunner is not a function 不符。不确定它在那里期望什么。

A​​VA 运行s 每个测试文件在其自己的进程中。 test.before() 应该用于设置仅由调用它的进程使用的固定装置。

听起来您想进行可在测试文件/进程中重复使用的设置。理想情况下,这是可以避免的,因为您最终可能会在不同测试的执行之间创建难以检测的依赖关系。

不过,如果这是您的需要,那么我建议使用 pretest npm 脚本,当您执行 npm test.

时,它会自动 运行

在您的 package.json 中,您可以先 运行 安装脚本...

"scripts": {
    "test": "node setup-test-database.js && ava '*.test.js'"
}

然后...

  • 在那个 setup-test-database.js 文件中,让它满足您所有的引导需求,并保存一个 test-config.json 文件,其中包含您需要传递给测试的任何内容。
  • 在每个测试中,您只需添加 const config = require('./test-config.json'); 即可访问所需的数据。