Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(jest-worker): postMessage error handler in child threads #14437

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Fixes

- `[jest-core]` Fix typo in `scheduleAndRun` performance marker ([#14434](https://github.com/jestjs/jest/pull/14434))
- `[jest-worker]` Additional error wrapper for `parentPort.postMessage` to fix unhandled `DataCloneError`. ([#14437](https://github.com/jestjs/jest/pull/14437))

### Chore & Maintenance

Expand Down
21 changes: 21 additions & 0 deletions packages/jest-worker/src/workers/__tests__/threadChild.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -365,3 +365,24 @@ it('throws if child is not forked', () => {
messagePort.emit('message', [CHILD_MESSAGE_CALL, true, 'fooThrows', []]);
}).toThrow('_worker_threads.parentPort.postMessage is not a function');
});

it('handle error if `postMessage` throws an error', () => {
messagePort.emit('message', [
CHILD_MESSAGE_INITIALIZE,
true,
'./my-fancy-worker',
]);

jest.mocked(messagePort.postMessage).mockImplementationOnce(() => {
throw mockError;
});

messagePort.emit('message', [CHILD_MESSAGE_CALL, true, 'fooWorks', []]);
expect(jest.mocked(messagePort.postMessage).mock.calls[1][0]).toEqual([
PARENT_MESSAGE_CLIENT_ERROR,
'TypeError',
'Boo',
mockError.stack,
{},
]);
});
9 changes: 8 additions & 1 deletion packages/jest-worker/src/workers/threadChild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,14 @@ function reportSuccess(result: unknown) {
throw new Error('Child can only be used on a forked process');
}

parentPort!.postMessage([PARENT_MESSAGE_OK, result]);
try {
parentPort!.postMessage([PARENT_MESSAGE_OK, result]);
} catch (err: any) {
// Handling it here to avoid unhandled `DataCloneError` rejection
// which is hard to distinguish on the parent side
// (such error doesn't have any message or stack trace)
reportClientError(err);
}
}

function reportClientError(error: Error) {
Expand Down