Skip to content

[Bug]: jest.mock not working with ESM support activated #13135

@iamWing

Description

@iamWing

Version

28.1.3

Steps to reproduce

  1. Clone my repo: https://github.com/iamWing/jest-esm-mock-issue
  2. npm I
  3. npm run start to verify Electron app shows up without issue
  4. npm t to run jest for the error

Expected behavior

Expecting Jest to mock functions app.on, app.whenReady and component BrowserWindow from electron, then execute the test cases with the mocked functions.

Actual behavior

Encountered TypeError: Cannot read properties of undefined (reading 'whenReady') when trying to run the test cases.

One possible reason I can think of is the imported module is being executed before jest.mock('electron', ...) in main.spec.js, hence Node is executing the line app.whenReady() in main.cjs with the non-mocked version.

Additional context

I originally tested with TypeScript & ts-jest with ESM support activated. The error I encountered there is very similar, so that I believe the error is from jest instead of ts-jest. See my comment on #10025 (#10025 (comment))

Environment

System:
    OS: macOS 12.5
    CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
  Binaries:
    Node: 16.16.0 - /usr/local/opt/node@16/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 8.13.2 - /usr/local/bin/npm
  npmPackages:
    jest: ^28.1.3 => 28.1.3

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