Automatic mock on 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:


class Foo {};

export default Foo;


import Foo from "./foo.js";

class FooStorage {
    constructor() { = []; // Array of Foo objects

export default FooStorage;


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

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


beforeEach(() => {

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


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.

Source: JavaSript – Stack Overflow

October 4, 2021
Category : News
Tags: ECMAScript 6 | javascript | jestjs | mocking | unit testing

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.