Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

413
Vistas
Automatic mock of an ES6 class fails (Jest, Vanilla JavaScript)

I have the class FooStorage that has an Array of Foo objects as a member variable. When testing FooStorage I want to mock the class Foo.
As described at ES6 Class Mocks, an automatic mock is all I need in my case. But when I try to mock the class, it doesn't seem to succeed. Instead when I try to reset the mock with mockClear(), I recieve an error message.

Below is the code and the output from jest:


foo.js

class Foo {};

export default Foo;

foostorage.js

import Foo from "./foo.js";

class FooStorage {
    constructor() {
        this.storage = []; // Array of Foo objects
    }
}

export default FooStorage;

foostorage.test.js

import Foo from "../src/foo.js";
import FooStorage from "../src/foostorage.js";

import { jest } from "@jest/globals";

jest.mock("../src/foo.js");

beforeEach(() => {
    Foo.mockClear();
});

test("if the Foo constructor hasn`t been called", () => {
    const storage = new FooStorage();
    expect(Foo).not.toHaveBeenCalled();
});

output

if the Foo constructor hasn`t been called

TypeError: Foo.mockClear is not a function

   7 |
   8 | beforeEach(() => {
>  9 |      Foo.mockClear();
     |          ^
  10 | });
  11 |
  12 | test("if the Foo constructor hasn`t been called", () => {

  at Object.<anonymous> (test/foostorage.test.js:9:6)

I have already tried to put jest.mock("../src/foo.js"); before import Foo from "../src/foo.js"; but the problem wasn't solved.


Edit:

I am using Jest v. 27.0.6 with jest-environment-node v. 27.0.6 and @types/jest v. 27.0.1.
I also use the nodejs arguments --experimental-modules and --experimental-vm-modules so that I can use ES6 imports. I don`t use Babel or anything else. Just plain JavaScript.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Automatic mocking is supposed to work like the documentation explains. If it doesn't and results in said error, this means that the module wasn't mocked, so it would fail with manual mock as well. This can happen because a mock wasn't performed correctly (different case or extension in module path), or jest.mock hoisting didn't work (most commonly because of misconfigured Babel transform).

The way this code differs from what's shown in the documentation is that jest global is commonly used, while here it is imported value, so it's not the same as using jest global. This is obvious and known reason for hoisting to work differently.

It can possibly be fixed by ordering dependencies in a way that doesn't interfere with expected execution order:

import { jest } from "@jest/globals";

jest.mock("../src/foo.js");

import Foo from "../src/foo.js";
...

The hoisting of jest.mock relies on undocumented, spec-incompliant hack that also depends on Jest version and a specific setup. It's not guaranteed to work because ES imports are expected to hoisted above other statements by specs, and there are no exclusions.

A dated but stable workaround is to switch to require that are regular JavaScript function calls and are evaluated as is:

let { jest } = require ("@jest/globals");

jest.mock("../src/foo.js");

let { default: Foo } = require("../src/foo.js");
...

And an efficient solution is to get rid of jest import and set up a generic Jest environment with respective globals, so jest.mock could be hoisted as expected regardless of Jest version and other circumstances.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda