Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Jest complete the async operation(s) in this Node test?

I have the following simple test setup:

test('what did I do to deserve this', async () => {
  expect.assertions(1)

  const data = await fetchData() // or fetchData2 
  expect(data).toBe('peanut butter')
})

async function fetchData () {
  return "peanut butter"
}

async function fetchData2 () {
  return knex.select('name').from('foos')
}

When I use fetchData jest finishes happily.
But when I use fetchData2 it complains of this:

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue.

The data variable does have the result from the db query, and other callers higher in the API resolve the query fine and continue the execution of other statements.

I have tried:

  1. the --detectOpenHandles flag but it doesn't show me anything.
  2. making the expect pass for fetchData2 in case it was the issue described here
  3. passing a done arg to the async function in test. It does exist, but calling it does not fix the warning.
  4. throwing try/catch blocks at it

Thanks for any help on making this happy.

Versions of things:

  • Node v11.1.0
  • "jest": "^23.6.0"
  • "knex": "^0.15.2"
like image 472
blu Avatar asked Nov 12 '18 17:11

blu


People also ask

How do you test asynchronous code with Jest?

You can combine async and await with .resolves or .rejects . await expect(fetchData()).rejects.toMatch('error'); }); In these cases, async and await are effectively syntactic sugar for the same logic as the promises example uses.

Do Jest tests run asynchronously?

Jest typically expects to execute the tests' functions synchronously. If we do an asynchronous operation, but we don't let Jest know that it should wait for the test to end, it will give a false positive.


2 Answers

To forcefully close Jest rather than DB Connection :

--forceExit

So my test script looked something like this,

"scripts": {
        "test": "jest --forceExit"
    }
like image 54
Dikshit Kathuria Avatar answered Nov 15 '22 23:11

Dikshit Kathuria


You need to call knex.destroy() in the end of the test suite to teardown connection pool.

like image 44
Mikael Lepistö Avatar answered Nov 15 '22 21:11

Mikael Lepistö