Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Race condition with Jest

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.

like image 659
spondbob Avatar asked Aug 09 '17 00:08

spondbob


People also ask

Can Jest run integration tests?

In general, Jest can run seven integration tests in parallel.

Is Jest good for API testing?

Jest is great for validation because it comes bundled with tools that make writing tests more manageable. While Jest is most often used for simple API testing scenarios and assertions, it can also be used for testing complex data structures.

Is Jest a test runner?

What is Jest? Jest is a testing framework created by Facebook. It is open source and it allows you to create JavaScript tests fast and easily. Jest is a very complete testing framework that comes not only with a test runner, but also with its own assertion and mocking library.

How do I use async await In Jest?

To enable async/await in your project, install @babel/preset-env and enable the feature in your babel. config. js file.


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.

like image 87
hernvnc Avatar answered Oct 01 '22 18:10

hernvnc