After looking into the questions:
I was able to do this:
package.json
{
"name": "my-project",
"jest": {
"testEnvironment": "./testEnvironment.js",
}
}
testEnvironment.js
const express = require('express');
// const NodeEnvironment = require('jest-environment-node'); // for server node apps
const NodeEnvironment = require('jest-environment-jsdom'); // for browser js apps
class ExpressEnvironment extends NodeEnvironment {
constructor(config, context) {
super(config, context);
}
async setup() {
await super.setup();
const app = express();
this.global.server = app.listen(0, "127.0.0.1", () => {
console.log(`Running express server on '${JSON.stringify(server.address())}'...`);
how to make setup() wait until app.listen callback is finished,
i.e., the server has properly started.
});
app.use(express.static('../testfiles'));
}
async teardown() {
this.global.server.close();
await super.teardown();
}
runScript(script) {
return super.runScript(script);
}
}
module.exports = ExpressEnvironment;
How to make setup() wait until app.listen() callback is finished, i.e., the server has properly started?
Before, when I was using beforeAll(), my code was working fine because I could use the done() async callback passed by beforeAll():
const express = require('express');
const app = express();
var server;
beforeAll(async (done) => {
server = app.listen(0, "127.0.0.1", () => {
console.log(`Running express server on '${JSON.stringify(server.address())}'...`);
done();
});
app.use(express.static('../testfiles'));
});
afterAll(() => {
server.close();
});
How would be the equivalent to the beforeAll done() callback on the NodeEnvironment setup() function?
You can do this by awaiting the listen even, wrapping it in a promise, and calling the promise resolve as the callback to the server listen
const app = express();
let server;
await new Promise(resolve => server = app.listen(0, "127.0.0.1", resolve));
this.global.server = server;
You could also put a custom callback that will just call the promise resolver as the third argument to the app.listen() and it should run that code then call resolve if you need some sort of diagnostics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With