Prompt.js
import { unstable_usePrompt as usePrompt } from 'react-router-dom';
// eslint-disable-next-line react/prop-types
export default function Prompt({ when, message }) {
usePrompt({ when, message });
return null;
}
Prompt.test.js
import {
createMemoryRouter,
RouterProvider,
} from 'react-router-dom';
import renderer from 'react-test-renderer';
import Prompt from '../Prompt';
const mockedUsePrompt = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
unstable_usePrompt: () => mockedUsePrompt,
}));
describe('Prompt', () => {
it('should call usePrompt with parameter', () => {
const router = createMemoryRouter(
[
{
path: '/',
element: <Prompt when message="Are you sure?" />,
},
],
{ initialEntries: ['/'] },
);
const component = renderer.create(
<RouterProvider router={router} />,
);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
expect(mockedUsePrompt).toHaveBeenCalledWith({ when: true, message: 'Are you sure?' });
});
});
How can I check calling usePrompt with arguments?
this line expect(mockedUsePrompt).toHaveBeenCalledWith({ when: true, message: 'Are you sure?' }); doesn't work
You didn't mock
unstable_usePrompt
correctly. See below working example:Prompt.js
:Prompt.test.js
:Test result: