我正在尝试为我的组件编写快照测试
在我的组件中,我有 useParams()
运行测试时,它返回一个未定义的错误:
TypeError: Cannot read property 'match' of undefined
20 | const [value, setValue] = useState();
21 | const { show, changeDetails } = props;
> 22 | const { id } = useParams();
| ^
组件位于
<Switch>
<Route
exact
path="/myroute/:id"
component={() => (
<>
<ModuleDetails />
</>
)}
/>
</Switch>
和 test.js 就像
it('renders correctly the assessment show page', () => {
const history = createMemoryHistory();
history.push('/myroute/1');
let tree = renderer
.create(
<Router history={history}>
<ModuleDetails />
</Router>
)
.toJSON();
expect(tree).toMatchInlineSnapsot(``);
});
答案 0 :(得分:1)
const TESTS = [
['reminderEmail', new Map<string, TestValue>([
['subject', { test: 'equal', expected: 'Kindly complete your setup' }],
['headers', new Map([
['X-Link', { test: 'equal', expected: 'someUrl' }],
['X-Template-Name', { test: 'equal', expected: 'reminderFirst' }],
['X-Template-Version', { test: 'equal', expected: 'someVersion' }],
])],
['html', [
{ test: 'include', expected: "Here's your reminder" },
{ test: 'include', expected: 'someUrl' },
{ test: 'include', expected: 'someUrl' },
{ test: 'include', expected: 'device' },
]],
['text', [
{ test: 'include', expected: "Here's your reminder" },
{ test: 'notInclude', expected: 'someUrl' },
{ test: 'notInclude', expected: 'someUrl' },
{ test: 'notInclude', expected: 'utm_source=email' },
]],
])],
];
答案 1 :(得分:0)
您需要将组件包装在 Router
中,useParams
使用来自路由器上下文的某些东西(可能是历史对象),没有路由器 - 没有上下文。
https://reactrouter.com/web/guides/testing
而且已经有人回答了How to test components using new react router hooks?