I am using Vitest as my testing framework in a project.
I have multiple test files in the project, let's say A.spec.ts and B.spec.test. I am using the standard test script (vitest run --no-threads --coverage) to test my code. I want to run a certain function (to purge and clean the testing database), before and after all the test suites are run (i.e. before all the tests in A.spec.ts and B.spec.ts, and after them as well).
Is there any way to achieve the same? I read about the methods like beforeAll and afterAll, but they work in the context of a file, and thus do not help with my use case.
You need to create a setup file in the directory of your likings (e.g. /tests/setup.ts)
Then, you need to link this file in the vitest config. For example, if your vitest config file is vitest.config.ts then it should look something like this:
export default defineConfig({
test: {
setupFiles: ['/tests/setup.ts'],
...
Finally, in your setup.ts (or whatever is your file), you call the beforeEach and afterEach method, just like you would in any of your tests:
beforeEach(() => {
// Do something here
})
afterEach(() => {
// Do something here
})
This works on vitest v0.32.2 don't know about earlier versions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With