我必须测试一个组件,它根据URL路径参数中的国家和语言呈现。所以我想看看组件是否根据参数的变化正确呈现。
我正在模拟useParams并设置一些适用于大多数测试的必需值。现在,对于一个特定的情况,我需要更改参数。
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: () => ({
language: 'IT'
})
}));
如何在测试中覆盖语言?
谢谢你
3条答案
按热度按时间ddrv8njm1#
您可以使用
<MemoryRouter initialEntries>
来取代useParams
,例如:MyComponent.js
*MyComponent.test.js
*在线演示
8ulbf1ek2#
根据Jest文档上的此页面,尝试以下操作
lymgl2op3#
yes Include the Router in your App component; Always render the App component in your tests (never child components like Locations); Navigate to your pages in tests by finding and clicking links on the page The positives of this approach: you don’t need to read the rest of this post 🙃 (and your test setup will be less complicated). The negatives: you can’t immediately load a routing history (the current page and previous pages) in test setup; you need to go through all the user interactions to build the history.