我希望在jest测试套件之间使用共享资源。我在网上阅读,发现这可能是解决方案。但是每个测试文件都会调用setup。
我有两个测试文件links.test.js和‘subscritnos.test.js’。我通常用一个命令jest来调用它们。
问题是我的自定义环境custom-environment.js的custom-environment.js函数
const NodeEnvironment = require('jest-environment-node');
const MySql = require('../../lib/databases/myslq/db');
class CustomEnvironment extends NodeEnvironment {
constructor(config) {
super(config)
}
async setup() {
await super.setup();
console.log(`Global Setup !!!!!!!!!`);
this.global.gObject = "I am global object"
this.global.liveUsers = await new MySql("Live Users");
this.global.stageUsers = await new MySql("Stage Users");
}
async teardown() {
console.log(`Global terdown !!!!!!!!!`);
await super.teardown();
this.global.gObject = "I am destroyed";
this.global.liveUsers.closeConnection();
this.global.stageUsers.closeConnection();
}
runScript(script) {
return super.runScript(script)
}
}
module.exports = CustomEnvironment;为每个测试调用两次:
全球设置全球设置ERROR>>>错误:侦听EADDRINUSE:地址已在使用127.0.0.1:3306
因此,它试图建立到同一个端口的第二个连接,而我可以简单地使用现有的连接。
在我看来,它的工作方式和定义没有什么区别。
beforeAll(async () => {
});
afterAll(() => {
});钩子。
因此,最后的问题是:使用jest命令(因此运行所有测试套件),我如何为所有测试调用安装函数并在它们之间共享全局对象?
发布于 2020-06-27 12:15:54
setup和teardown确实是针对每个测试套件执行的,类似于顶级beforeAll和afterAll。
测试套件在单独的进程中运行。为每个测试套件初始化测试环境,例如jsdom环境为每个测试套件提供假DOM实例,它们之间不能交叉污染。
如文件所述,
注意: TestEnvironment是沙箱。每个测试套件将在它们自己的TestEnvironment中触发安装/拆卸。
该环境不适合全局设置和拆卸。应该使用globalTeardown。它们适合于设置和关闭服务器实例,这就是文档示例所显示的:
// setup.js
module.exports = async () => {
// ...
// Set reference to mongod in order to close the server during teardown.
global.__MONGOD__ = mongod;
};
// teardown.js
module.exports = async function () {
await global.__MONGOD__.stop();
};因为这发生在父进程中,所以__MONGOD__在测试套件中不可用。
https://stackoverflow.com/questions/62609776
复制相似问题