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:
- In
App.js
import Foo from 'components/Foo'
importsFoo/index.js
. Inside components create__mocks__/Foo/index.js
and export mock component. - Create a setup file for jest in project root
jest.setup.js
and declarejest.mock('src/components/Foo')
- In jest config, add option
setupFilesAfterEnv: ['./jest.setup.js']