【问题标题】:How to override default mock of useParams in jest如何在玩笑中覆盖 useParams 的默认模拟
【发布时间】:2022-01-11 21:16:47
【问题描述】:
我必须测试一个基于 url 路径参数中的国家和语言呈现的组件。所以我想知道组件是否根据参数的变化正确呈现。
我正在模拟 useParams 并设置一些适用于大多数测试的必需值。现在针对特定情况,我需要更改参数。
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: () => ({
language: 'IT'
})
}));
如何覆盖测试中的语言?
谢谢
【问题讨论】:
标签:
react-hooks
jestjs
mocking
【解决方案1】:
根据 Jest 文档中的 page,尝试以下操作
// create a separate mock function that you can access from tests
// NOTE: the name must start with `mock` and is case sensitive
const mockUseParams = jest.fn().mockReturnValue({
language: 'IT',
});
// mock the module using the mock function created above
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: mockUseParams,
}));
it('should behave differently when the params change', () => {
mockUseParams.mockReturnValueOnce({
language: 'EN',
});
// test implementation
});