Jest&supertest ApI testing returning TypeError: app.address is not a function
The reason is your server
passed into supertest
is undefined
. supertest
will use app.address()
internally, see this line. That's why it throw an error:
TypeError: app.address is not a function
If you want to import the server
dynamically, You should change:
let server;beforeAll(async () => { server = import('../../../../src/index')})
to:
let server;beforeAll(async () => { const mod = await import('../../../../src/index'); server = (mod as any).default;});
E.g.
index.ts
:
import express from 'express';const app = express();app.post('/api/users/auth/register', (req, res) => { res.status(400).json({ errArray: [] });});const port = 3001 || process.env.PORT;const server = app.listen(port, () => console.log(`Server running on port ${port}`));export default server;
index.test.ts
:
import request from 'supertest';describe('/api/users/auth', () => { let server; beforeAll(async () => { const mod = await import('./'); server = (mod as any).default; }); afterAll((done) => { if (server) { server.close(done); } }); it('should return 400 if email is invalid', async () => { const res = await request(server) .post('/api/users/auth/register') .send({ email: 'nomail', password: 'validpassword123', name: 'name', }); expect(res.status).toBe(400); expect(res.body).toHaveProperty('errArray'); });});
Integration test result with coverage report:
☁ jest-codelab [master] ⚡ npx jest --coverage --verbose /Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/54230886/index.test.ts PASS src/stackoverflow/54230886/index.test.ts (10.306s) /api/users/auth ✓ should return 400 if email is invalid (56ms) console.log src/stackoverflow/54230886/index.ts:437 Server running on port 3001----------|----------|----------|----------|----------|-------------------|File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |----------|----------|----------|----------|----------|-------------------|All files | 100 | 50 | 100 | 100 | | index.ts | 100 | 50 | 100 | 100 | 9 |----------|----------|----------|----------|----------|-------------------|Test Suites: 1 passed, 1 totalTests: 1 passed, 1 totalSnapshots: 0 totalTime: 11.875s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/54230886