Skip to content

Commit

Permalink
fix: Additional error wrapper for postMessage to avoid unhandled `D…
Browse files Browse the repository at this point in the history
…ataCloneError`
  • Loading branch information
dj-stormtrooper committed Aug 21, 2023
1 parent eb61702 commit a2a54a0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
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 a2a54a0

Please sign in to comment.