Skip to content

[Bug]: Global setup and teardown throws an error when the message property is unwritable #14112

@david-szabo97

Description

@david-szabo97

Version

29.5.0

Steps to reproduce

Create a class that extends Error, then make the message property unwritable - as an example, you can make it a getter.

Example repository:

  1. Clone repository: https://github.com/david-szabo97/jest-message-getter-issue
  2. Install dependencies: npm i
  3. Run tests: npm test
  4. Error thrown:
TypeError: Cannot set property message of Error which has only a getter
    at runGlobalHook (node_modules\@jest\core\build\runGlobalHook.js:114:25)

Expected behavior

I expect to see the error that happened, not an error from Jest's code.

Actual behavior

A new error is thrown from the try-catch block because the message property is not writable. Therefore, the "original error" will never show up.

This affects both global setup and global teardown scripts because the same code executes both modules.

Additional context

Relevant code line

error.message = `Jest: Got error running ${moduleName} - ${modulePath}, reason: ${error.message}`;

In the real world, Zod uses a message getter: https://github.com/colinhacks/zod/blob/502384e56fe2b1f8173735df6c3b0d41bce04edc/src/ZodError.ts#L272-L274

Although, I don't really like Zod's approach about making the message property a getter, but neither the fact that Jest modifies the value of the message property. In my opinion, it should be Jest's responsibility to only modify the message property, when possible. Or use a custom Error object. Or use the cause property (unfortunately, it is not supported in Node v14).

Environment

System:
    OS: Windows 10 10.0.22621
    CPU: (20) x64 13th Gen Intel(R) Core(TM) i5-13600KF
  Binaries:
    Node: 18.14.2 - ~\AppData\Local\Volta\tools\image\node\18.14.2\node.EXE
    Yarn: 1.22.18 - ~\AppData\Local\Volta\tools\image\yarn\1.22.18\bin\yarn.CMD
    npm: 9.5.0 - ~\AppData\Local\Volta\tools\image\node\18.14.2\npm.CMD
  npmPackages:
    jest: ^29.5.0 => 29.5.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions