0

I have a node.js (v10.8.0) app running express, and am testing it with mocha/chai. I'd like mocha to run tests every time there is a file change.

My database (postgres) is initialized like this in db.js:

const pg = require('pg-promise')();
const db = pg('postgres://localhost:5432/myapp');

class DB {
  createNewUser(data) {...

My package.json file looks like this:

  "scripts": {
    "test": "cross-env NODE_ENV=development mocha",
    "dev": "cross-env NODE_ENV=development nodemon --exec babel-node src/index.js"
  },

My tests pass when I run npm test. But if I run npm test -- --watch, it will run the first test and pass, but on the first change it will re-instantiate the database and produce the following error:

WARNING: Creating a duplicate database object for the same connection.
    at Object.<anonymous> (/Path/to/my/code/src/db.js:4:12)
    at Module._compile (internal/modules/cjs/loader.js:689:30)

What can I do to fix this?

Mark Karavan
  • 2,654
  • 1
  • 18
  • 38

1 Answers1

0

If this warning were produced in the actual code, you would need to worry about it yes. But in your tests, the situation is synthetic, caused by creation of multiple Database objects, each containing the exact same connection details.

So here're your options:

  • Make sure in your tests that you do not create Database more than once
  • Tell the library not to throw any warnings, by specifying noWarnings: true within the initialization options, i.e. const pgp = require('pg-promise')({noWarnings: true})
  • Just ignore it, if your tests work.

See also: Where should I initialize pg-promise.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138