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?' });
});
});
型
如何检查使用参数调用usePrompt?
这行 expect(mockedNotice Prompt).toHaveBeenCalledWith({ when:true,message:'Are you sure?' }); 不起作用
1条答案
按热度按时间q5lcpyga1#
你没有正确地模拟
unstable_usePrompt
。参见下面的工作示例:Prompt.js
:字符串
Prompt.test.js
:型
测试结果:
型