mswjs / data

Data modeling and relation library for testing JavaScript applications.
https://npm.im/@mswjs/data
MIT License
822 stars 52 forks source link

Open handle error when using with Jest #308

Open soapwong703 opened 3 days ago

soapwong703 commented 3 days ago

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/@mswjs+data@0.15.0_typescript@5.1.6/node_modules/@mswjs/data/lib/extensions/sync.js:69:19)
      at factory (node_modules/.pnpm/@mswjs+data@0.15.0_typescript@5.1.6/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.

kettanaito commented 2 days ago

Hi, @soapwong703. Thanks for reporting this!

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