Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a function before all the test modules in Vitest

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.

like image 906
Eshaan Aggarwal Avatar asked Mar 09 '26 19:03

Eshaan Aggarwal


1 Answers

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.

like image 122
butaminas Avatar answered Mar 11 '26 07:03

butaminas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!