Race condition with Jest

Viewed 2198

I am testing my graphql endpoint that is doing query to DB through sequelize with Jest. But sometimes I found my test files kind of having a race condition. What I mean is, for every test file I have a setup DB block such as

beforeAll(async () => {
  await database.sequelize.sync({force: true})
  await database.User.create(user)
})

so that in the test file I can easily predict what is in DB. Sometimes this causes an issue where every test file trying to do .sync(). One test file will create DB while the other performs drop DB.

Even though I have used await through out my tests, this doesn't look like guarantee that the test file will wait for another test to finish.

What would be the best approach here to make sure every test file can predict what is in DB by having clean DB while at the same time not conflicting with other tests? Is it actually a good idea for a test to wait for others to finish? It seems not optimised to me as it will take more time to run the whole test suite.

1 Answers

How many workers are you using? Tests run serially within the same test file, but not between different test files.

There are a number of options to try: 1 - Creating and using a unique DB for every test file. 2 - Making them all run serially with the --runInBand flag. I'm not sure but maybe --maxWorkers=1 does it as well.

Related