Skip to content

Commit 6da3bbb

Browse files
committed
Implement custom handler for unhandled promise rejections in Jest tests
1 parent 05c662a commit 6da3bbb

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

jest.config.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,16 @@
1+
const _ = process;
2+
3+
// @ts-expect-error we need to put this inside jest.config.js,
4+
// since it's being read before the process object is replaced by the jest runner.
5+
// More info:
6+
// https://johann.pardanaud.com/blog/how-to-assert-unhandled-rejection-and-uncaught-exception-with-jest/
7+
// https://github.com/jestjs/jest/issues/5620
8+
// https://github.com/jestjs/jest/issues/11165
9+
// https://codesandbox.io/p/devbox/z9qdp4?migrateFrom=zzjfzz
10+
global._onUnhandledRejection = handler => {
11+
_.on('unhandledRejection', handler);
12+
};
13+
114
import { createDefaultEsmPreset } from 'ts-jest/dist/presets/create-jest-preset.js';
215

316
const tsJestTransformCfg = createDefaultEsmPreset().transform;

src/__tests__/unhandled.test.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,22 @@
77

88
import DataLoader from '../index.ts';
99
import { describe, it, expect, jest } from '@jest/globals';
10-
import process from 'node:process';
1110

1211
describe('Unhandled rejections', () => {
1312
it('Not catching a primed error is an unhandled rejection', async () => {
14-
//process.removeAllListeners('unhandledRejection');
1513
const handler = jest.fn();
16-
process.on('unhandledRejection', handler); //detectOpenHandles
14+
// @ts-expect-error need to use injected _onUnhandledRejection as the original process.on may have been overridden by Jest
15+
global._onUnhandledRejection(handler); //detectOpenHandles
1716

1817
const identityLoader = new DataLoader<number, number>(async keys => keys);
1918
identityLoader.prime(1, new Error('Error: 1'));
2019

21-
// Ignore result.
2220
const promise = identityLoader.load(1);
2321

2422
await new Promise(resolve => setTimeout(resolve, 1000));
2523
expect(handler).toHaveBeenCalled();
24+
25+
// Prevent Jest from complaining about the unhandled rejection
2626
promise.catch(() => {});
2727
});
2828
});

0 commit comments

Comments
 (0)