全局设置和拆卸
¥Global setup and teardown
¥Stability: 1.0 - Early development
测试运行器支持指定一个模块,该模块将在执行所有测试之前进行评估,并可用于设置测试的全局状态或基座。这对于准备资源或设置多个测试所需的共享状态非常有用。
¥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
函数¥A
globalSetup
function which runs once before all tests start -
所有测试完成后运行一次的
globalTeardown
函数¥A
globalTeardown
function which runs once after all tests complete
从命令行运行测试时,使用 --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.