Skip to content

Commit

Permalink
fix(jest-worker): postMessage error handler in child threads (#14437)
Browse files Browse the repository at this point in the history
  • Loading branch information
dj-stormtrooper committed Aug 23, 2023
1 parent 642267f commit 834d9d6
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
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

0 comments on commit 834d9d6

Please sign in to comment.