How to run the server automatically when executing the test cases?
I want to run the server automatically through the code so i just need to run the test cases.
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
Closing due inactivity
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 ?
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
launchandstopfunctions. - You can use child_process to
execa new node process with your server file, store the ChildProcess object in a variable and then usekillto stop it inside the teardown / teardownAll. - You can use Worker threads to start the server in a thread and then
terminateit.
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()
},
}
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.