I have the following Jest test that runs against a Polka server:
import polka, {Polka} from 'polka';
import { agent as request } from 'supertest';
function brokenMiddleware(req, res, next) {
throw new Error("foobar");
}
describe('integreration', () => {
describe('middleware', () => {
let testPolka: Polka;
beforeEach(() => {
testPolka = polka()
.use(brokenMiddleware)
.get('/', async (req, res) => {
res.end('Hello world');
});
});
afterEach(() => {
if(testPolka) {
if(testPolka.server) {
testPolka.server.close()
}
}
});
it('should return active request', async () => {
// Get active requests from the tracker
const response = await request(testPolka.handler)
.get('/')
.set('Accept', 'application/json');
await expect(response.headers["Content-Type"]).toMatch(/json/);
await expect(response.status).toEqual(200);
});
});
});
Because the middleware is broken, jest
never correctly exists.
If you run:
npx jest --detectOpenHandles test/polka.spec.ts
You will get:
Jest has detected the following 1 open handle potentially keeping Jest from exiting:
● TCPSERVERWRAP
34 | // Get active requests from the tracker
35 | const response = await request(testPolka.handler)
> 36 | .get('/')
| ^
37 | .set('Accept', 'application/json');
38 |
39 | await expect(response.headers["Content-Type"]).toMatch(/json/);
at Test.serverAddress (node_modules/supertest/lib/test.js:48:35)
at new Test (node_modules/supertest/lib/test.js:34:14)
at TestAgent.<computed> [as get] (node_modules/supertest/lib/agent.js:47:17)
at test/polka.spec.ts:36:10
at test/polka.spec.ts:8:71
at Object.<anonymous>.__awaiter (test/polka.spec.ts:4:12)
at Object.<anonymous> (test/polka.spec.ts:32:51)
at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/@jest/core/build/runJest.js:387:19)
at _run10000 (node_modules/@jest/core/build/cli/index.js:408:7)
at runCLI (node_modules/@jest/core/build/cli/index.js:261:3)
What would be the correct way to write Polka middleware and Jest tests so that
Jest tests exit cleanly even if middleware is not functioning correctly
Broken middleware does not cause issues for Polka in production