CodeceptJS icon indicating copy to clipboard operation
CodeceptJS copied to clipboard

How to run the server automatically when executing the test cases?

Open PoojaMittal27 opened this issue 9 years ago • 5 comments

I want to run the server automatically through the code so i just need to run the test cases.

PoojaMittal27 avatar Apr 14 '17 09:04 PoojaMittal27

We have bootstrap/teardown option which can be used for such cases. Launch a server in bootstrap and stop it in teardown http://codecept.io/hooks/#bootstrap-teardown

DavertMik avatar Apr 18 '17 16:04 DavertMik

Closing due inactivity

APshenkin avatar Jun 01 '17 09:06 APshenkin

Hi guys, I can boostrap a express server by config of codeceptjs, but how can I turn it off when all the tests is done ?

wahengchang avatar Jul 25 '18 04:07 wahengchang

In case someone hits this issue from search engine like I did, there are multiple ways you can approach this in practice:

  • You can expose an API for your server, which is kinda implied in the documentation (e.g. your server module exports launch and stop functions.
  • You can use child_process to exec a new node process with your server file, store the ChildProcess object in a variable and then use kill to stop it inside the teardown / teardownAll.
  • You can use Worker threads to start the server in a thread and then terminate it.

The last option can go kinda like this:

// codecept.conf.js
//...
const {Worker, isMainThread} = require('worker_threads')


let serverWorker = null

function startServer() {
  serverWorker = new Worker('./index.js') // assuming the main entry file of your server is in ./index.js file
  return new Promise((resolve, reject) => {
    serverWorker.once('online', resolve)
    serverWorker.once('error', reject)
  })
}
async function stopServer() {
  if (serverWorker) {
    await serverWorker.terminate()
  }
}

exports.config = {
  // ... other CodeceptJS options
  async bootstrapAll() {
    await startServer()
  },
  async bootstrap() {
    if (isMainThread) {
      await startServer()
    }
  },
  async teardown() {
    if (isMainThread) {
      await stopServer()
    }
  },
  async teardownAll() {
    await stopServer()
  },
}

jnv avatar Dec 18 '20 11:12 jnv

Even easier: Use jest-process-manager. Despite the name, it is not dependent on Jest in any way and it has very convenient API for bootstrap and teardown.

jnv avatar Dec 23 '20 08:12 jnv