'CRA - Jest mock loses the mock implementation
I'm trying to use __mocks__.
src/shared/state/use-some-state.ts
export const useSomeState = () => {
return { value: 6 };
}
which is exported from an index.ts file:
export * from './use-some-state`
And I've created a mock file like this:
src/shared/state/__mocks__/index.ts
export const useSomeState = jest.fn(() => ({value: 1}))
When this mock is used in a component's test the mock implementation is undefined:
src/modules/my-component.tsx
export const MyComponent = () => {
const { value } = useSomeState();
return <div>{value}</div>
}
The test for MyComponent looks like this:
my-component.test.tsx
import React from 'react';
import { render } from '@testing-library/react';
import {MyComponent} from '../my-component';
jest.mock('shared/state');
describe('<MyComponent />', () => {
let container: HTMLElement;
beforeEach(() => {
({ container } = render(<MyComponent />));
});
it('should render correctly', () => {
expect(container.firstChild).toMatchSnapshot();
});
});
This errors because undefined can't be destructured in the MyComponent as the return from useSomeState is undefined and not {value: 1} as it is in the mock. useSomeState is a jest function but it's lost it's mock implementation.
If I remove the jest.fn from the mock and just use a function that returns { value: 1 } then it works fine, so why does the mock implementation get lost.
p.s. If I import the use-some-state.ts into my-component.test.tsx file and log useSomeState() it works as expected, its just in MyComponent where it doesn't.
Solution 1:[1]
Thanks to jonrsharpe the answer was adding:
"jest": {
"resetMocks": false,
}
to package.json.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | adamdaly |
