Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mocha hangs after tests have finished

I'm running mocha in nodejs, testing an asynchronous function, I didn't forget to call done, but after the test passes mocha just hangs there, waiting for nothing. Even the function that I placed for after() has finished, but mocha doesn't exit until I CTRL+C it.

Here is the code:

describe("tests the user_handler", () => {
  beforeEach(resetDB);
  after(resetDB);

  it("returns null when searching for a user with an id that does not exists", (done) => {
    userHandler.findUserById( {user_id: "U-1234567"} )
      .then((result) => {
        expect(result).to.be.null;
        done()
      })
  })
})

and here is the output:

tomk@tomk-Latitude-7480 ~/workspace/fundme/server (login_with_github) $ npm test

> [email protected] test /home/tomk/workspace/fundme/server
> mocha tests/*.spec.js



  tests the user_handler
resetDB called
resetDB finished
    ✓ returns null when searching for a user with an id that does not exists
resetDB called
resetDB finished


  1 passing (64ms)

^CTerminated

If it's relevant (though I don't think so), the function being tested is using a promisified version of mysqlConnectionPool from the mysql2 library

Here is the code for the resetDB function I'm using for the beforeEach and after:

function resetDB() {
  console.log("resetDB called")
  command =
    "mysql" +
    " --defaults-extra-file=" + mysql_conf_file +
    " --host " + process.env['MYSQL_HOSTNAME'] +
    " -D fundme < " + testing_db_file_location;
  cp.execSync(command);
  console.log("resetDB finished")
}

any ideas to what I might have forgot?

like image 488
Tom Klino Avatar asked Jun 26 '18 15:06

Tom Klino


Video Answer


1 Answers

Since you mention you are using a mysqlConnectionPool. I'm guessing that you may not be closing out the pool which is causing your program to continue on waiting for all the connections to close out.

Judging by the docs: Using connection pools

// Don't forget to release the connection when finished!

releasing the connection after you are done is critical. Check and make sure that you are doing this after() each or all of your tests:

// For pool initialization, see above
pool.getConnection(function(err, conn) {
   // Do something with the connection
   conn.query(/* ... */);
   // Don't forget to release the connection when finished!
   pool.releaseConnection(conn);
})

Or, since this is only a test file, closing all the connections in the after will make sure mocha stops at the end:

after(() => { mysqlConnectionPool.end() })
like image 83
zero298 Avatar answered Nov 11 '22 10:11

zero298