Skip to content

jest.mock does not mock an ES module without BabelΒ #10025

Open
@aldeed

Description

@aldeed

πŸ› Bug Report

In an ES module Node project, with no Babel, jest.mock works when the mocked module is a node_modules package that exports CommonJS, but it isn't working for me mocking an ES module exported from a file in the same project.

(It's possible that an NPM package that only exports ES modules has the same issue. I didn't try that case.)

To Reproduce

Steps to reproduce the behavior:

Click Run in the repl, or here's a simple example:

// main.js
import secondary from "./secondary.js";

export default function main() {
  return secondary();
}

// secondary.js
export default function secondary() {
  return true;
}

// test.js
import { jest } from "@jest/globals";

jest.mock("./secondary.js");

let main;
let secondary;
beforeAll(async () => {
  ({ default: main } = await import("./main.js"));
  ({ default: secondary } = await import("./secondary.js"));
});

test("works", () => {
  secondary.mockReturnValueOnce(false); // TypeError: Cannot read property 'mockReturnValueOnce' of undefined
  expect(main()).toBe(false);
});

Expected behavior

jest.mock(filename) should mock the exports from filename when the test file and the Node project are both ES modules (type: "module")

Link to repl or repo (highly encouraged)

https://repl.it/repls/VerifiableOfficialZettabyte

envinfo

  System:
    OS: macOS 10.15.4
    CPU: (4) x64 Intel(R) Core(TM) i5-4278U CPU @ 2.60GHz
  Binaries:
    Node: 12.16.3 - ~/.nvm/versions/node/v12.16.3/bin/node
    Yarn: 1.21.1 - /usr/local/bin/yarn
    npm: 6.14.4 - ~/DevProjects/reaction/api-utils/node_modules/.bin/npm
  npmPackages:
    jest: ^26.0.1 => 26.0.1 

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