I've developed a server class that looks like this:
import express, { Request, Response } from 'express';
export default class Server {
server: any;
exp: any;
constructor() {
this.exp = express();
this.exp.get('/', (_req: Request, res: Response) => {
res.json('works');
});
}
start(): void {
this.server = this.exp.listen(3000);
}
stop(): void {
this.server.close();
}
}
For end-to-end testing, I'm utilizing supertest. My goal is to initiate my application beforeAll tests and terminate it once the tests are completed.
While it's straightforward to achieve this using beforeAll and afterAll by instantiating the Server class and invoking the start and close methods, I have numerous controllers to test, making it inconvenient to start and stop the server for each test file.
After exploring the documentation, I came across the setupFiles and setupFilesAfterEnv, but I struggled with stopping the server since the instance isn't shared between the two files.
Here's an example of a test file:
import supertest from 'supertest';
describe('Album Test', () => {
let app: App;
beforeAll(async (done) => {
app = new App();
await app.setUp(); // establishing database connection
done();
});
afterAll(async (done) => {
await app.close();
app.server.stop();
done();
});
const api = supertest('http://localhost:3000');
it('Hello API Request', async () => {
const result = await api.get('/v1/user');
expect(result.status).toEqual(200);
...
});
});
Although this approach works well, I find myself duplicating these beforeAll and afterAll methods in every test file. Is there a way to declare them only once?
Thank you