Jest async setup before each test file

Viewed 1179

I have to do an async setup before each test file in jest (specifically to start a MongoMemoryServer each time).

  1. Using setupFiles isn't working because does not handle async work. Passing a global Promise won't work because I have to set the db uri string before requiring my db module (I don't want to mock it after await a Promise, that's just bad).
  2. The official guide uses testEnvironment and sets up the mongo server with globalSetup. Strangely enough the docs say

Note: TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment.

But that is not true, because setup and teardown are global.

Tests run concurrently, and I need to insert documents in beforeAll in each file and that causes write errors.

I am stunned by the fact that so many people use the Node/MongoDB/jest stack and yet I stumble upon so many problems.

Anyway, thank you!

1 Answers

You're confusing setup/teardown methods of TestEnvironment (which will be executed before/after every test file) with globalSetup/globalTeardown of Jest runner (which will be executed before/after all tests).

Related