0

I develop an API server with Hapi. I use @hapi/lab for testing. I have different test files for different API modules/routes.

There is a server initialization in each test file. A DB connection is created when the server is initialized, consequently, multiple DB connections are created at the same time when I try to test the server. And I got warning like that:

WARNING: Creating a duplicate database object for the same connection.
at Object.register (/home/.../node_modules/hapi-pg-promise/index.js:19:20)
at internals.Server.register (/home/.../node_modules/@hapi/hapi/lib/server.js:453:35)
at async Object.exports.compose (/home/.../node_modules/@hapi/glue/lib/index.js:46:9)
at async createServer (/home/.../server.js:10:115)
at async Immediate.<anonymous> (/home/.../node_modules/@hapi/lab/lib/runner.js:662:17)

So, is there an approach, how to test a Hapi server in multiple files without multiple server connections?

ekorolev
  • 1
  • 2
  • See [Where should I initialize pg-promise](https://stackoverflow.com/questions/34382796/where-should-i-initialize-pg-promise). Also, strictly for tests, you can disable the warning with the `noWarnings` [initialization option](https://vitaly-t.github.io/pg-promise/module-pg-promise.html). – vitaly-t Dec 10 '19 at 02:42

1 Answers1

0

You will have to lazy load the servr. let's assume you have a function serverFactory which returns the server. you could do this

let serverFactoryObj;

function getServerFactory() {
  if (!serverFactoryObj) {
    serverFactoryObj = serverFactory();
  }

  return serverFactoryObj;
}

This way, no matter how many times you test the endpoints, you will always have a single instance of server. Ideally you should always test with single instance rather than creating/stopping server for each test.

Ashish Modi
  • 7,529
  • 2
  • 20
  • 35