After looking into the questions:
- Async setup of environment with Jest
- window/document not defined in import
- Configure Jest global tests setup with .ts file (TypeScript)
- About app.listen() callback
- How to write a Jest configuration file
- NodeJS: How to get the server's port?
- https://alligator.io/nodejs/serving-static-files-in-express/
- Promisify server.listen
- Unexpected token import in custom node environment
- How to access class properties of Jest Test Environment inside child test?
- Cannot create custom TestEnvironment in Jest
- globalSetup is executed in different context than tests
- global beforeAll
- How to test url change with Jest
- Specify window.location for each test file for Jest
- window.location.href can't be changed in tests
- global beforeAll
- How do I test a single file using Jest?
- https://basarat.gitbook.io/typescript/intro-1/jest
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?