Here is what I export to the test file (as well as to the entry point):
// app.ts // много импортов class App { public readonly app: Express = express(); constructor() { this.app.use(/*всякие стандартные мидлвары*/); this.app.use('/api/user', userApi); // и прочие роуты } } const server = new Server( new App().app ); export default server; Here is the test file:
import request = require('supertest'); import app from '../../../lib/app'; describe('User login test', () => { afterAll(() => { app.close(); }); test('Send invalid token', async (done) => { const res = await request(app) .post('/api/user/v3/login') .send({data: 'woBxaXd1cS0tLVVxMTU0NDUyMjA0ODA4Mw=='}) .set('Content-Type', 'application/json'); expect(res.status).toBe(403); done(); }); // ну и аналогичные, ожидающие другие статус-коды }); I run the tests with the following command:
"scripts": { "test": "cross-env NODE_ENV=test jest --detectOpenHandles" } I also use jest.config.js:
module.exports = { preset: 'ts-jest', testEnvironment: 'node', }; After running the tests, the following message is displayed:
PASS test/user/v2/user-login-routes-v2.test.ts (0.273s) User login test √ Login new user (204ms) √ Send existing token (23ms) √ Send invalid token (30ms) √ Send empty token (16ms) Test Suites: 1 passed, 1 total Tests: 4 passed, 4 total Snapshots: 0 total Time: 30.452s, estimated 46s Ran all test suites. And yet, no more messages to the console does not fall. But the invitation does not appear - I stop the process via ctrl + C.
If you run without the --detectOpenHandles flag, then after passing the tests, the following message appears:
Jest did not exit one second after the test run has completed. This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue. But with the flag does not show anything (when I did not use the done callback for example, messages appeared).
How do I complete the process after passing the tests?
Expressinstance that you run continues to work after the test is completed, despite theapp.close()construct, in theafterAllmethod. - SergeyEgorovnpm startcommand, and stop at thenpm stopcommand. And so that this can be done with a single command, for example, after entering thenpm testin the console, run the backend, run the tests and stop the backend then you can use thepm2package. It also has a software interface too. That is, any details of the start and stop scripts can be written in the sameJavaScript. - SergeyEgorov pm