全局设置和拆卸


【Global setup and teardown】

稳定性: 1.0 - 早期开发

测试运行器支持指定一个模块,该模块将在所有测试执行之前进行评估,并可用于为测试设置全局状态或夹具。这对于准备资源或设置多个测试所需的共享状态非常有用。

【The test runner supports specifying a module that will be evaluated before all tests are executed and can be used to setup global state or fixtures for tests. This is useful for preparing resources or setting up shared state that is required by multiple tests.】

此模块可以导出以下任意值:

【This module can export any of the following:】

  • 一个 globalSetup 函数,会在所有测试开始前运行一次
  • 一个在所有测试完成后运行一次的 globalTeardown 函数

在从命令行运行测试时,可以使用 --test-global-setup 标志来指定该模块。

【The module is specified using the --test-global-setup flag when running tests from the command line.】

// setup-module.js
async function globalSetup() {
  // Setup shared resources, state, or environment
  console.log('Global setup executed');
  // Run servers, create files, prepare databases, etc.
}

async function globalTeardown() {
  // Clean up resources, state, or environment
  console.log('Global teardown executed');
  // Close servers, remove files, disconnect from databases, etc.
}

module.exports = { globalSetup, globalTeardown };// setup-module.mjs
export async function globalSetup() {
  // Setup shared resources, state, or environment
  console.log('Global setup executed');
  // Run servers, create files, prepare databases, etc.
}

export async function globalTeardown() {
  // Clean up resources, state, or environment
  console.log('Global teardown executed');
  // Close servers, remove files, disconnect from databases, etc.
}

如果全局设置函数抛出错误,将不会运行任何测试,并且进程将以非零退出代码退出。在这种情况下,全局拆卸函数将不会被调用。

【If the global setup function throws an error, no tests will be run and the process will exit with a non-zero exit code. The global teardown function will not be called in this case.】