问题
I want to use shared resources between jest test suites. I read in the internet and found that this could be the solution. But the setup
is invoked per each test file.
I have two test files links.test.js
and 'subscritpions.test.js'. I usually call them with one command jest
and that all.
The problem is that the setup
function of my custom environment 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;
is called twice for each test:
Global Setup !!!!!!!!! Global Setup !!!!!!!!! ERROR>>> Error: listen EADDRINUSE: address already in use 127.0.0.1:3306
So it tries to establish second connection to the same port - while I could simply use the existing connection.
The way it works seems to me makes no difference from defining
beforeAll(async () => {
});
afterAll(() => {
});
hooks.
So to wrap up, the question is: Using jest
command (thus running all test suits), how can I invoke setup function once for all test and share global objects across them?
回答1:
setup
and teardown
are indeed executed for each test suite, similarly to top-level beforeAll
and afterAll
.
Test suites run in separate processes. Test environment is initialized for each test suite, e.g. jsdom
environment provides fake DOM instance for each suite and cannot be cross-contaminated between them.
As the documentation states,
Note: TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment.
The environment isn't suitable for global setup and teardown. globalSetup and globalTeardown should be used for that. They are appropriate for setting up and shutting down server instances, this is what documentation example shows:
// 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();
};
Since this happens in parent process, __MONGOD__
is unavailable in test suites.
来源:https://stackoverflow.com/questions/62609776/jest-initialize-and-shared-objects-once-per-test-suite-and-across-test-cases