javascriptnode.jstestingjestjssupertest

Jest - some tests fail on the first run, but pass on the second and third run


I write tests with jest and supertest npm, in node server.

when I run all the tests together, some of the tests fails:

failing tests

choosing in the terminal to run just the failed tests, run them and they pass.

passing tests

now, if I choose in the terminal to run all the tests again, all tests passes but the following error is shown:

Watch Usage: Press w to show more.(node:9484) UnhandledPromiseRejectionWarning

error: unhandled promise rejection

I use the beforeEach() to delete the db and create the initial db to be the same for each test.

this is setUpDb():

const setUpDb = async () => {
    await neo4jContext('MATCH (n) DETACH DELETE n')
    await usersRepository.addUser(user1)
    await usersRepository.addUser(user2)
    await productsRepository.addProduct({ userId: user1.id, product: product1 })
    await productsRepository.addProduct({ userId: user1.id, product: product2 })
    await storesRepository.addStore({
        userId: user1.id, store: store1, products: [product3]
    })
    await storesRepository.addStore({
        userId: user1.id, store: store2, products: [product3]
    })
}

//

beforeEach(setUpDb)

using --runInBand the tests run sequently, one after the other, so there should not be a mix-up state.

this is the config in the package.json

"scripts": {
    "start": "node src/index.js",
    "debug": "env-cmd -f ./config/dev.env node inspect src/index.js",
    "dev": "env-cmd -f ./config/dev.env nodemon src/index.js",
    "test": "env-cmd -f ./config/test.env jest --watch --runInBand"
  },
  "jest": {
    "testEnvironment": "node",
    "testTimeout": 50000
  }

I tried looking into it but all I found was tests that affect a common state, and therefor different result appears when run alone. I'm don't think this is the issue here, because all of the above.

thx for anyone reaching out!


Solution

  • it happened because I had a test with async function in it, that i didn't put await before it's execution:

    it('should do something', async () => {
    const asyncFunc = async () => console.log('async func needs await on exe')
    
    //wrong
    asyncFunc()
    //right
    await asyncFunc()
    })