gpt4 book ai didi

reactjs - 在测试中使用 MemoryRouter 时,未在 props 上设置“match”属性

转载 作者:行者123 更新时间:2023-12-03 13:42:14 26 4
gpt4 key购买 nike

我一直在尝试让测试适用于react-router v4。我已经采取了记录的基本example here并为其编写了以下测试:

import React from 'react';
import { Topic } from './App';
import { MemoryRouter } from 'react-router-dom'
import TestRenderer from 'react-test-renderer';

test('it renders', () => {
TestRenderer.create(
<MemoryRouter initialEntries={['/topics/props-v-state']} initialIndex={0}>
<Topic/>
</MemoryRouter>
);
});

我收到错误:“TypeError:无法读取未定义的属性“params””,我将其解释为 match属性(property)不被设置在Topic的 Prop 上组件由 MemoryRouter 。我的依赖项是:

"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-router-dom": "^4.2.2",
"react-scripts": "1.1.0"
},
"devDependencies": {
"babel-jest": "22",
"babel-preset-es2015": "6",
"babel-preset-react": "6",
"jest": "22",
"react-test-renderer": "16"
},

我想我可以做<Topic match={{url: '/topics/props-v-state'}} />但是documentation here似乎暗示这可以通过 MemoryRouter 来完成。

非常感谢任何帮助。

最佳答案

matchhistorylocation 属性仅传递给由 Route 组件渲染的组件。需要访问这些属性的其他组件可以通过调用 withRouter 进行包装。 HOC。

你的例子可以写成:

import React from 'react';
import { Topic } from './App';
import { MemoryRouter, withRouter } from 'react-router-dom';
import TestRenderer from 'react-test-renderer';

const RTopic = withRouter(Topic);

test('it renders', () => {
TestRenderer.create(
<MemoryRouter initialEntries={['/topics/props-v-state']} initialIndex={0}>
<RTopic/>
</MemoryRouter>
);
});

作为替代方案,您的应用程序模块可以直接导出由 withRouter 包装的组件。

关于reactjs - 在测试中使用 MemoryRouter 时,未在 props 上设置“match”属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48403959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com