Jest manual mocks does not use mock file in CRA Jest manual mocks does not use mock file in CRA reactjs reactjs

Jest manual mocks does not use mock file in CRA


I see that your file structure is incorrect. The __mocks__ directory should immediately under components

src/|- components/|-- Foo.js |-- __mocks__|--- Foo.jsx|- App.js|- App.test.js

Now Foo.js on main module directory can be something like this

function Foo() {    return (            <h1> Foo</h1>    );  }  export default Foo;

And __mocks/Foo.js can be

console.log("Mock imported");function Foo() {    return (            <h1> Mock</h1>    );  }  export default Foo;

App.test.js will contain jest.mock call

import { render, screen } from '@testing-library/react';import App from './App';jest.mock("./components/Foo");test('renders learn react link', () => {   render(<App />);  const linkElement = screen.getByText(/Mock/i); // Check that MOCK component is called  expect(linkElement).toBeInTheDocument();});

See the git repository for working samplehttps://github.com/meera/jest_mock


Creating mock is a 3 step process:

  1. In App.js import Foo from 'components/Foo' imports Foo/index.js. Inside components create __mocks__/Foo/index.js and export mock component.
  2. Create a setup file for jest in project root jest.setup.js and declare jest.mock('src/components/Foo')
  3. In jest config, add option setupFilesAfterEnv: ['./jest.setup.js']