jest: [Bug]: globalsCleanup causes issues with some deps, can't be properly turned off

Version

30.0.0

Steps to reproduce

git clone https://github.com/EDM115-alt/repro-5.git
pnpm i
pnpm test
If you can't run the commands for some reason, here's the output :
PS C:\Users\EDM115\Desktop\repro-5> pnpm test         

> repro@1.0.0 test C:\Users\EDM115\Desktop\repro-5
> run-s --continue-on-error test:base test:noCleanup test:hackishFix


> repro@1.0.0 test:base C:\Users\EDM115\Desktop\repro-5
> node --experimental-vm-modules --expose-gc ./node_modules/jest/bin/jest.js --runInBand --logHeapUsage --config ./jest.config.base.js

Determining test suites to run...Server built
 FAIL  ./test.js
  ● Test suite failed to run

    TypeError: Cannot assign to read only property 'Symbol($$jest-protect-from-deletion)' of object '[object Object]'
        at Function.assign (<anonymous>)

      at new T (node_modules/.pnpm/@influxdata+influxdb3-client@1.1.0/node_modules/node_modules/@protobuf-ts/runtime/build/es2015/message-type.js:26:74)
      at new Ve (node_modules/.pnpm/@influxdata+influxdb3-client@1.1.0/node_modules/@influxdata/influxdb3-client/src/generated/flight/google/protobuf/timestamp.ts:157:9)
      at node_modules/.pnpm/@influxdata+influxdb3-client@1.1.0/node_modules/@influxdata/influxdb3-client/src/generated/flight/google/protobuf/timestamp.ts:237:26

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.442 s
Ran all test suites.
Server closed
(node:2404) ExperimentalWarning: VM Modules is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 ELIFECYCLE  Command failed with exit code 1.

> repro@1.0.0 test:noCleanup C:\Users\EDM115\Desktop\repro-5
> node --experimental-vm-modules --expose-gc ./node_modules/jest/bin/jest.js --runInBand --logHeapUsage --config ./jest.config.noCleanup.js

Determining test suites to run...Server built
 FAIL  ./test.js
  ● Test suite failed to run

    TypeError: Cannot assign to read only property 'Symbol($$jest-protect-from-deletion)' of object '[object Object]'
        at Function.assign (<anonymous>)

      at new T (node_modules/.pnpm/@influxdata+influxdb3-client@1.1.0/node_modules/node_modules/@protobuf-ts/runtime/build/es2015/message-type.js:26:74)
      at new Ve (node_modules/.pnpm/@influxdata+influxdb3-client@1.1.0/node_modules/@influxdata/influxdb3-client/src/generated/flight/google/protobuf/timestamp.ts:157:9)
      at node_modules/.pnpm/@influxdata+influxdb3-client@1.1.0/node_modules/@influxdata/influxdb3-client/src/generated/flight/google/protobuf/timestamp.ts:237:26

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.44 s
Ran all test suites.
Server closed
(node:19220) ExperimentalWarning: VM Modules is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 ELIFECYCLE  Command failed with exit code 1.

> repro@1.0.0 test:hackishFix C:\Users\EDM115\Desktop\repro-5
> node --experimental-vm-modules --expose-gc ./node_modules/jest/bin/jest.js --runInBand --logHeapUsage --config ./jest.config.hackishFix.js

Determining test suites to run...Server built
  console.log
    Server built

      at log (server.js:9:11)

(node:21236) ExperimentalWarning: VM Modules is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 PASS  ./test.js (38 MB heap size)
  √ working (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.47 s, estimated 1 s
Ran all test suites.
Server closed
ERROR: "test:noCleanup" exited with 1.
 ELIFECYCLE  Test failed. See above for more details.

Expected behavior

The property deletion feature introduced in Jest 30 (https://github.com/jestjs/jest/blob/main/packages/jest-util/src/garbage-collection-utils.ts) is a great idea, and marking stuff as protected to not delete them is great too !
However it seems like it tries to edit immutable objects, causing the tests to fail.
And disabling the testEnvironmentOptions.globalsCleanup should prevent this behavior altogether (like in Jest <30) but it doesn’t.

Actual behavior

Some external functions (like here from @influxdata/influxdb3-client) gets marked as protected from deletion which is nice, but uh-oh it can’t be edited : Cannot assign to read only property 'Symbol($$jest-protect-from-deletion)' of object '[object Object]'

Setting testEnvironmentOptions.globalsCleanup to “off” doesn’t change things, and we have to use a hackish fix :

  • Create a file containing this :
    // jest.protect-fix.js
    const proto = Object.prototype
    const sym = Object.getOwnPropertySymbols(proto).find(
      (s) => String(s) === "Symbol($$jest-protect-from-deletion)",
    )
    
    if (sym) {
      delete proto[sym]
    }
    
  • Use it among the setupFiles of your config since they run before the globalSetup as it seems :
    const config = {
      testEnvironment: "node",
      setupFiles: ["<rootDir>/jest.protect-fix.js"],
      testTimeout: 5000,
      globalSetup: "<rootDir>/setup.js",
      globalTeardown: "<rootDir>/teardown.js",
      modulePathIgnorePatterns: ["<rootDir>/node_modules"],
    }
    
    export default config
    

Additional context

We had this issue using ts-jest and TS files but in the repro it is also happening with bare JS

Environment

System:
    OS: Windows 11 10.0.26100
    CPU: (12) x64 12th Gen Intel(R) Core(TM) i7-1255U
  Binaries:
    Node: 22.16.0 - C:\nvm4w\nodejs\node.EXE
    npm: 11.4.1 - C:\nvm4w\nodejs\npm.CMD
    pnpm: 10.11.0 - ~\AppData\Local\pnpm\pnpm.CMD
  npmPackages:
    jest: ^30.0.0 => 30.0.0

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Reactions: 2
  • Comments: 16 (8 by maintainers)

Commits related to this issue

Most upvoted comments

Published Jest 30.0.1 which should hopefully resolve the issue if you turn the cleanup mode to off.

Just to quickly explain, we, and specifically @eyalroth, have been trying to identify ways to reduce memory leaks that are caused by user code in tests that cannot be cleaned up because things attach themselves to global state and stick around for the full test run, even across individual tests since we re-use processes/threads. Unfortunately in JavaScript it is hard to do that safely. Thank you for your bug reports that help inform the direction to go in.

Wait, why is the symbol for the cleanup even enumerable?

@cpojer It’s not.

The package is trying to create a new prototype that is identical to Object’s prototype, but with an additional property.

They read all of Object’s prototype property descriptors (with Object.getOwnPropertyDescriptors) and then try to assign them to a new empty object ({}). It works okay with the spread operator ({...ojb}) but not with Object.assign).

Thinking about it now, that might actually make all of their messages protected from cleanup 😬

As I suspected, but couldn’t verify without debugging, this is a bug with lodash.omit

Closing the loop here - The issue was resolved after elastic-builder was updated to use the latest (and patched) version of Lodash.

We are running into similar issues

@khitrenovich I’m afraid there’s not enough information here for me to identify the issue.

Could you please provide more information and preferability a minimal reproducible project?

@tobyhinloopen Thanks for the report! This looks the same issue but just with Jest’s own code (jest-matchers-utils).

We are running into similar issues comparing POJOs coming from elastic-builder’s toJSON() override (see sample below). Is that an issue with the matcher implementation or something I should report to the elastic-builder maintainers?

    expect(received).toEqual(expected) // deep equality

    - Expected  - 0
    + Received  + 1

    @@ -9,7 +9,8 @@
              ],
              "query": "test*",
              "type": "phrase_prefix",
            },
          },
    +     Symbol($$jest-protect-from-deletion): Array [],
        },
      }

      1325 |     it('should return multi-match prefix query', () => {
      1326 |       const result = ElasticSearchServices.getMultiMatchPrefixQuery(query, fields);
    > 1327 |       expect(result.toJSON()).toEqual({ bool: { minimum_should_match: 1, should: { multi_match: { query, fields, type: 'phrase_prefix' } } } });
           |                               ^
      1328 |     });
      1329 |   });
      1330 |

      at Object.<anonymous> (spec/aws/ElasticSearchServices.spec.ts:1327:31)

For me, this also throws the error:

  // boom!
  it("jest json", async () => {
    const response = await fetch("http://localhost:4000/generate-json?size=10");
    const json = await response.json();
    expect({ json }).toEqual({})
  });

  // no problem bro!
  it("jest text->json", async () => {
    const response = await fetch("http://localhost:4000/generate-json?size=10");
    const text = await response.text();
    const json = JSON.parse(text);
    expect({ json }).toEqual({})
  });
  ● HttpTool › jest json

    TypeError: Cannot assign to read only property 'Symbol($$jest-protect-from-deletion)' of object '[object Object]'

      29 |     const response = await fetch("http://localhost:4000/generate-json?size=10");
      30 |     const json = await response.json();
    > 31 |     expect({ json }).toEqual({})
         |                      ^
      32 |   });
      33 |
      34 |   it("jest text->json", async () => {

      at Object.<anonymous> (scrappy-core/test/tools/HttpTool.test.ts:31:22)

  ● HttpTool › jest text->json

    expect(received).toEqual(expected) // deep equality

    - Expected  -  1
    + Received  + 10

    - Object {}
    + Object {
    +   "json": Array [
    +     Object {
    +       "number": 0.018372268730619812,
    +     },
    +     Object {
    +       "number": 0.15242744600387936,
    +     },
    +   ],
    + }

      36 |     const text = await response.text();
      37 |     const json = JSON.parse(text);
    > 38 |     expect({ json }).toEqual({})
         |                      ^
      39 |   });
      40 | });
      41 |

      at Object.<anonymous> (scrappy-core/test/tools/HttpTool.test.ts:38:22)

Environment:

// root project
{
  "devDependencies": {
    "@types/jest": "^30.0.0",
    "jest": "^30.0.0",
    "jest-environment-jsdom": "^30.0.0",
    "jest-util": "^30.0.0",
    "jsdom": "^26.1.0",
    "start-server-and-test": "^2.0.12",
    "ts-jest": "^29.4.0",
    "typescript": "^5.8.3"
  }
}
// workspace package
  "dependencies": {
    "lodash": "^4.17.21",
    "zod": "^3.25.0"
  },
  "devDependencies": {
    "@types/lodash": "^4"
  }
// jest config for package
    {
      displayName: 'scrappy-core',
      preset: 'ts-jest',
      testEnvironment: 'node',
      roots: ['<rootDir>/scrappy-core'],
      testMatch: ['**/test/**/*.test.ts']
    },

Let’s just say my “huh!?” was immeasurable, hah.

This looks like a bug in protobuf-ts.

I will open a bug report for them.

In the meanwhile I’ll open a PR to avoid setting the protection symbol when globalsCleanup: off.


Bug details

While their source code uses the spread operator:

{ ...baseDescriptors, [MESSAGE_TYPE]: { value: this }

their build actually transpiles it to:

Object.assign(Object.assign({}, baseDescriptors), { [MESSAGE_TYPE]: { value: this } })

Eventually, this code is problematic:

const props = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));

Object.assign({}, props); // this will cause the error

What it does is:

  1. Get all the properties of Object’s prototype, which include the new Jest deletion symbol.
    1. The properties are in the format of { <propertyKey>: <propertyDefinition> }
  2. Try to assign (override) the properties of a new object ({})
    1. This fails because the new Jest deletion symbol is non-writable (unlike the rest of Object’s prototype props).

I don’t think there is any guarantee that Object’s prototype props will all be writable, so their code is dangerous regardless of Jest.