Skip to content

Commit 673f19c

Browse files
authored
[jest-circus, jest-jasmine2] Fix error-handler restore, --expand for assert diffs, and generator test context (#16347)
1 parent d6db09f commit 673f19c

12 files changed

Lines changed: 204 additions & 11 deletions

File tree

‎.github/copilot-instructions.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ node ../../packages/jest-cli/bin/jest.js --no-cache
4747

4848
CI runs the test matrix with `nick-fields/retry` (10-min timeout, up to 3 retries on flake) across Ubuntu/macOS/Windows × Node 18/20/22/24/25/26. If a test is consistently failing locally but green in CI, suspect a retry-masked flake.
4949

50+
`codecov/patch` and `codecov/project` report before the four `Node LTS on Ubuntu with coverage (N/4)` shards have uploaded, so their numbers mean nothing until those jobs finish; both are advisory anyway (`require_ci_to_pass: false`, `target: auto`). Coverage is measured only in the process running the suite, so a line reachable only through an e2e fixture always reads as uncovered.
51+
5052
### Test gotchas worth memorizing
5153

5254
- **Snapshot updates with ANSI colors**: many snapshots contain chalk-rendered ANSI escape sequences. Always update snapshots with `FORCE_COLOR=1 yarn jest <path> -u` so the color output is preserved. Running without `FORCE_COLOR=1` strips the sequences and produces wrong snapshots.

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,11 @@
1616

1717
- `[expect, jest-message-util, jest-pattern, jest-regex-util, jest-util]` Revert `node:` protocol imports to restore webpack/browser-bundle compatibility ([#16167](https://github.com/jestjs/jest/pull/16167))
1818
- `[expect]` Widen `toMatchObject` and `objectContaining` parameter type from `Record<string, unknown>` to `object` so class instances are accepted ([#16196](https://github.com/jestjs/jest/pull/16196))
19+
- `[jest-circus]` Call a generator test body with the shared test context, so `this` matches what a regular test function receives ([#16347](https://github.com/jestjs/jest/pull/16347))
20+
- `[jest-circus]` Capture the error listeners of the parent process instead of the in-sandbox `process`, so listeners registered before the test file survive teardown and sandbox listeners no longer leak onto the parent ([#16347](https://github.com/jestjs/jest/pull/16347))
1921
- `[jest-circus]` Clear `currentlyRunningTest` after skipped and todo tests ([#16342](https://github.com/jestjs/jest/pull/16342))
2022
- `[jest-circus]` Prevent late `done()` callbacks from affecting later test or hook invocations ([#16343](https://github.com/jestjs/jest/pull/16343))
23+
- `[jest-circus, jest-jasmine2]` Honor `--expand` when formatting `node:assert` failures, instead of always collapsing the diff ([#16347](https://github.com/jestjs/jest/pull/16347))
2124
- `[jest-circus, jest-jasmine2, jest-message-util]` Serialize the inner errors of an `AggregateError` into `failureMessages`, `retryReasons` and `unhandledErrors`, so `--json` output and reporter annotations include them ([#16316](https://github.com/jestjs/jest/pull/16316))
2225
- `[jest-circus, jest-snapshot]` Keep snapshot state and counts correct when a test retries ([#16344](https://github.com/jestjs/jest/pull/16344))
2326
- `[@jest/create-cache-key-function]` Include the caller support flags in the generated key, so a transformer that emits ESM or CJS based on them no longer shares one cache entry between the two ([#16331](https://github.com/jestjs/jest/pull/16331))

‎e2e/__tests__/failures.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,26 @@ test('works with node assert', () => {
4747
expect(summary).toMatchSnapshot();
4848
});
4949

50+
test('node assert diffs honor --expand', () => {
51+
// The unchanged keys are printed in full ahead of the diff either way, so
52+
// only the `Difference:` section tells the two modes apart.
53+
const diffSection = (stderr: string) =>
54+
cleanStderr(stderr).split('Difference:').at(-1)!;
55+
56+
const collapsed = diffSection(
57+
runJest(dir, ['assertionErrorExpand.test.js']).stderr,
58+
);
59+
const expanded = diffSection(
60+
runJest(dir, ['assertionErrorExpand.test.js', '--expand']).stderr,
61+
);
62+
63+
expect(collapsed).toContain('@@');
64+
expect(collapsed).not.toContain('"key9": 9');
65+
66+
expect(expanded).not.toContain('@@');
67+
expect(expanded).toContain('"key9": 9');
68+
});
69+
5070
test('works with assertions in separate files', () => {
5171
const {stderr} = runJest(dir, ['testMacro.test.js']);
5272

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
'use strict';
9+
10+
const assert = require('assert');
11+
12+
test('wide object diff', () => {
13+
const shared = {};
14+
for (let index = 0; index < 12; index++) {
15+
shared[`key${index}`] = index;
16+
}
17+
18+
assert.deepStrictEqual(
19+
{...shared, changed: 'received'},
20+
{...shared, changed: 'expected'},
21+
);
22+
});
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
import {EventEmitter} from 'node:events';
9+
import type * as Process from 'node:process';
10+
import {
11+
injectGlobalErrorHandlers,
12+
restoreGlobalErrorHandlers,
13+
} from '../globalErrorHandlers';
14+
15+
const errorEvents = [
16+
'uncaughtException',
17+
'unhandledRejection',
18+
'rejectionHandled',
19+
] as const;
20+
21+
// Circus runs inside the VM, where the ambient `process` is the sandbox copy
22+
// made by `createProcessObject` — a different emitter from the `parentProcess`
23+
// the handlers are installed on. A plain emitter stands in for the parent.
24+
const makeParentProcess = () => {
25+
const emitter = new EventEmitter();
26+
return {emitter, parentProcess: emitter as unknown as typeof Process};
27+
};
28+
29+
describe('injectGlobalErrorHandlers', () => {
30+
test('snapshots the listeners of the parent process, not the ambient one', () => {
31+
const {emitter, parentProcess} = makeParentProcess();
32+
const parentListener = () => {};
33+
for (const event of errorEvents) {
34+
emitter.on(event, parentListener);
35+
}
36+
37+
const originalHandlers = injectGlobalErrorHandlers(parentProcess);
38+
39+
expect(originalHandlers.uncaughtException).toEqual([parentListener]);
40+
expect(originalHandlers.unhandledRejection).toEqual([parentListener]);
41+
expect(originalHandlers.rejectionHandled).toEqual([parentListener]);
42+
43+
for (const event of errorEvents) {
44+
expect(emitter.listeners(event)).not.toContain(parentListener);
45+
expect(emitter.listeners(event)).toHaveLength(1);
46+
}
47+
});
48+
49+
test('restores the parent process listeners it replaced', () => {
50+
const {emitter, parentProcess} = makeParentProcess();
51+
const parentListener = () => {};
52+
for (const event of errorEvents) {
53+
emitter.on(event, parentListener);
54+
}
55+
56+
restoreGlobalErrorHandlers(
57+
parentProcess,
58+
injectGlobalErrorHandlers(parentProcess),
59+
);
60+
61+
for (const event of errorEvents) {
62+
expect(emitter.listeners(event)).toEqual([parentListener]);
63+
}
64+
});
65+
66+
test('keeps a restored `once` listener one-shot', () => {
67+
const {emitter, parentProcess} = makeParentProcess();
68+
let calls = 0;
69+
emitter.once('uncaughtException', () => {
70+
calls++;
71+
});
72+
73+
restoreGlobalErrorHandlers(
74+
parentProcess,
75+
injectGlobalErrorHandlers(parentProcess),
76+
);
77+
78+
emitter.emit('uncaughtException', new Error('first'));
79+
emitter.emit('uncaughtException', new Error('second'));
80+
81+
expect(calls).toBe(1);
82+
expect(emitter.listeners('uncaughtException')).toHaveLength(0);
83+
});
84+
85+
test('does not leak listeners added inside the sandbox onto the parent process', () => {
86+
const {emitter, parentProcess} = makeParentProcess();
87+
const originalHandlers = injectGlobalErrorHandlers(parentProcess);
88+
89+
// A `setupFiles` script registering on the sandbox `process` must not be
90+
// restored onto the parent.
91+
const sandboxListener = () => {};
92+
for (const event of errorEvents) {
93+
process.on(event, sandboxListener);
94+
}
95+
96+
try {
97+
restoreGlobalErrorHandlers(parentProcess, originalHandlers);
98+
99+
for (const event of errorEvents) {
100+
expect(emitter.listeners(event)).toHaveLength(0);
101+
}
102+
} finally {
103+
for (const event of errorEvents) {
104+
process.removeListener(event, sandboxListener);
105+
}
106+
}
107+
});
108+
});

‎packages/jest-circus/src/__tests__/utils.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,31 @@ test('makeRunResult keeps the unserialized unhandled errors', () => {
142142
expect(result.unhandledErrors[0]).toBe(error.stack);
143143
});
144144

145+
test('a generator test body receives the shared test context', async () => {
146+
const rootDescribe = makeDescribe(ROOT_DESCRIBE_BLOCK_NAME);
147+
const testContext = {fromHook: 'hook value'};
148+
let sawSharedContext = false;
149+
const circusTest = makeTest(
150+
function* (this: Circus.TestContext) {
151+
sawSharedContext = this === testContext;
152+
} as unknown as Circus.TestFn,
153+
undefined,
154+
false,
155+
'generator test',
156+
rootDescribe,
157+
undefined,
158+
new Error('async error'),
159+
false,
160+
);
161+
162+
await callAsyncCircusFn(circusTest, testContext, {
163+
isHook: false,
164+
timeout: 1000,
165+
});
166+
167+
expect(sawSharedContext).toBe(true);
168+
});
169+
145170
test('a late done callback does not affect a later invocation', async () => {
146171
const rootDescribe = makeDescribe(ROOT_DESCRIBE_BLOCK_NAME);
147172
let firstDone: Circus.DoneFn = () => {};

‎packages/jest-circus/src/globalErrorHandlers.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,17 @@ const rejectionHandledListener: NodeJS.RejectionHandledListener = (
3131
export const injectGlobalErrorHandlers = (
3232
parentProcess: typeof Process,
3333
): Circus.GlobalErrorHandlers => {
34-
const uncaughtException = [...process.listeners('uncaughtException')];
35-
const unhandledRejection = [...process.listeners('unhandledRejection')];
36-
const rejectionHandled = [...process.listeners('rejectionHandled')];
34+
// `rawListeners` keeps the wrapper a `once` listener is registered through,
35+
// so restoring it does not turn it into a permanent one.
36+
const uncaughtException = [
37+
...parentProcess.rawListeners('uncaughtException'),
38+
] as Array<NodeJS.UncaughtExceptionListener>;
39+
const unhandledRejection = [
40+
...parentProcess.rawListeners('unhandledRejection'),
41+
] as Array<NodeJS.UnhandledRejectionListener>;
42+
const rejectionHandled = [
43+
...parentProcess.rawListeners('rejectionHandled'),
44+
] as Array<NodeJS.RejectionHandledListener>;
3745
parentProcess.removeAllListeners('uncaughtException');
3846
parentProcess.removeAllListeners('unhandledRejection');
3947
parentProcess.removeAllListeners('rejectionHandled');

‎packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ export const initialize = async ({
8484
getRunnerState().testTimeout = globalConfig.testTimeout;
8585
}
8686
getRunnerState().maxConcurrency = globalConfig.maxConcurrency;
87+
getRunnerState().expand = globalConfig.expand;
8788

8889
getRunnerState().randomize = globalConfig.randomize;
8990
getRunnerState().seed = globalConfig.seed;

‎packages/jest-circus/src/utils.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,7 @@ export const callAsyncCircusFn = (
272272

273273
let returnedValue: Global.TestReturnValue;
274274
if (isGeneratorFunction(fn)) {
275-
returnedValue = co.wrap(fn).call({});
275+
returnedValue = co.wrap(fn).call(testContext);
276276
} else {
277277
try {
278278
returnedValue = fn.call(testContext);

‎packages/jest-jasmine2/src/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,8 @@ export default async function jasmine2(
274274
)
275275
.default({expand: globalConfig.expand});
276276

277+
jasmine.Spec.expand = globalConfig.expand;
278+
277279
if (globalConfig.errorOnDeprecated) {
278280
installErrorOnPrivate(environment.global);
279281
} else {

0 commit comments

Comments
 (0)