To set up a Jest configuration for testing an app that listens on a specific port, pass a script to globalSetup
. Then, create an agent in your test to make requests to the app using the same port.
- Introduce a global variable in your Jest configuration.
import type { Config } from 'jest';
export default async (): Promise<Config> => {
return {
...
globals: {
APP_PORT: findOpenTCPPort(), // You can implement this logic yourself or hardcode it
},
globalSetup: '<rootDir>/e2e.globalSetup.ts',
globalTeardown: '<rootDir>/e2e.globalTeardown.ts',
};
};
- Create typings for the new global variable in a
.d.ts
file. I named my file e2e.types.d.ts
and placed it in a types
directory.
declare global {
const APP_PORT: number;
}
export {};
- Ensure that the
*.d.ts
file is recognized by the TypeScript server.
{
"extends": "../tsconfig.json",
"compilerOptions": {
"typeRoots": ["../node_modules/@types/", "./types"]
}
}
- Add the script
e2e.globalSetup.ts
to create the NestJS app.
import { Test } from '@nestjs/testing';
module.exports = async function globalSetup(_, projectConfig) {
const module = Test.createTestingModule({ ... })
const moduleRef = await module.compile();
const app = moduleRef.createNestApplication();
await app.init();
await app.listen(projectConfig.globals.APP_PORT);
globalThis.APP = app;
};
- Include a
e2e.globalTeardown.ts
script to shut down the app.
module.exports = async function globalTeardown() {
await globalThis.APP.close();
process.exit();
};
- In your tests, create a supertest agent to interact with the app.
...
import request from 'supertest';
const agent = request(`http://localhost:${APP_PORT}`);
describe('[POST] /some/endpoint', () => {
it('400 - Missing parameters', async () => {
const response = await agent.post('/some/endpoint').send({});
expect(response.statusCode).toBe(HttpStatus.BAD_REQUEST);
});
});