问题
I have a Node.js project that I'm testing using Jest. I have several test files that have the same setup requirement. Previously, all these tests were in one file, so I just had a beforeAll(...)
that performed the common setup. Now, with the tests split into multiple files, it seems like I have to copy/paste that beforeAll(...)
code into each of the files. That seems inelegant - is there a better way to do this, ideally where I can just write my beforeAll(...)
/setup logic once, and "require" it from multiple test files? Note that there are other tests in my test suite that don't require this setup functionality, so I don't want to make all my tests run this setup (just a particular subset of test files).
回答1:
If you're using Jest >=20, you might want to look into creating a custom jest-environment
for the tests that require this common setup. This would be a module that extends either jest-environment-node
or jest-environment-jsdom
, and implements async setup()
, async teardown()
, and async runScript()
to do this setup work.
You can then add a @jest-environment my-custom-env
directive to those files that require this setup.
See the Jest config docs for testEnvironment for details on how to set this up; there's a simple example there.
回答2:
You can move your beforeAll
logic into one file and reference it in jest.config.js setupFilesAfterEnv
section:
module.exports = {
...
setupFilesAfterEnv: ['<rootDir>/testHelper.ts'],
...
}
https://jestjs.io/docs/en/configuration#setupfilesafterenv-array
回答3:
If you need a script to run before all your test files, you can use globalSetup
This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites.
in your jest.config.js
//jest.config.js
module.exports = {
...
testTimeout: 20000,
globalSetup: "./setup.js"
};
then create a file named setup.js
// setup.js
module.exports = async () => {
console.log("I'll be called first before any test cases run");
//add in what you need to do here
};
Docs
来源:https://stackoverflow.com/questions/47997652/jest-beforeall-share-between-multiple-test-files