Search code examples
expressunit-testingtestingjestjssupertest

Jest Supertest Tests fail if all are ran but pass if ran 1 by 1


I have a express.js application and I used jest and supertest-session to test my application since I need to test features that require a user to be authenticated. My tests have async methods and access a postgres db.

So, I have 3 tests. Lets say test1, test2, test3.

When I type 'npx jest' in the shell it runs all of the tests and 'test2' fails. But If i run 'npx jest test1', then 'npx jest test2',... they all pass. Even if it's in the same order that 'npx jest' runs the tests.

In all tests I have a afterAll that delete everything in my psql table. So, if test2 does something to 'table' then when it's done it just deletes all that it did so then next test has a clean table. However, when running 'npx jest' it runs all of the tests and another tests picks up a row that another test has created which results in a fail (it should be working with an empty table).

I ran the test that creates this rogue psql row and then checked my psql table and it has nothing in it.

Does 'npx jest' just run these tests concurrently? If so, how can I make it so that it doesn't.

Thank you.


Solution

  • Let me give a common comment here... The main problem is not the concurrency regime, but the tests itself. One of the main criteria for any unit-test is Independence; that means a test shouldn't share its state with other tests. If tests pass one by one but do not pass while general launch... they are not unit ones. It's good that you found a way out from the situation with runInBand, but it will become more and more painful to support that, and the best thing you can do is to break dependencies. Why do you really need to write to 'table'? Why don't you mock it? It would allow you to not care about deleting of test data. A clear test, no problems with concurrency.