data icon indicating copy to clipboard operation
data copied to clipboard

Open handle error when using with Jest

Open soapwong703 opened this issue 1 year ago • 2 comments

I am trying to setup test cases with jest, but after the test was finished the process will stalled and does not exit.

Using the command jest --detectOpenHandles will show this error message preventing jest from exiting.

Jest has detected the following 1 open handle potentially keeping Jest from exiting:

  ●  MESSAGEPORT

      1 | import { factory, primaryKey } from "@mswjs/data";
      2 |
    > 3 | const db = factory({
        |                   ^
      4 |   user: {
      5 |     userCode: primaryKey(String),
      6 |     name: String,

      at Object.sync (node_modules/.pnpm/@[email protected][email protected]/node_modules/@mswjs/data/lib/extensions/sync.js:69:19)
      at factory (node_modules/.pnpm/@[email protected][email protected]/node_modules/@mswjs/data/lib/factory.js:50:12)
      at Object.<anonymous> (src/mocks/db.ts:3:19)
      at Object.<anonymous> (src/mocks/handlers/user.ts:13:52)
      at Object.<anonymous> (src/mocks/server.ts:12:54)
      at Object.<anonymous> (src/setupTests.ts:10:17)

Actual Code:

import { factory, primaryKey } from "@mswjs/data";

const db = factory({
  user: {
    userCode: primaryKey(String),
    name: String,
    rank: String,
    updateDate: () => new Date(),
  },
});


export default db;

After investigation, I found the issue should be related to the unclosed BroadcastChannel 'mswjs/data/sync' in this file: https://github.com/mswjs/data/blob/84d529e223a932bf6ab282efa9b79ad895018599/src/extensions/sync.ts#L75

I am suggesting to expose an method for user to manually close the broadcast channel after the test case is completed.

soapwong703 avatar Nov 19 '24 08:11 soapwong703

Hi, @soapwong703. Thanks for reporting this!

We need to .unref() the broadcast channel to free memory.

kettanaito avatar Nov 19 '24 22:11 kettanaito

Are there plans to fix this or is there a workaround besides --forceExit?

philcunliffe avatar Mar 05 '25 20:03 philcunliffe

Released: v1.0.0 🎉

This has been released in v1.0.0.

Get these changes by running the following command:

npm i @msw/data@latest

Predictable release automation by Release.

kettanaito avatar Sep 28 '25 18:09 kettanaito