我有一个带有 URL 参数的 React 组件。当我运行测试并安装组件时,参数始终未定义,因此破坏了测试。我尝试将它们硬编码为常量、 Prop ,但它仍然不起作用。我还可以尝试其他想法吗?
import React, { Component } from 'react';
class BarcodePage extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { SKU, ID } = this.props.match.params
}
render() {
return (
<h1>Barcode view {SKU} {ID}</h1>
);
}
}
export default BarcodePage;
import React from 'react';
import { shallow } from 'enzyme';
import BarcodePage from './BarcodePage';
const component = mount(
<BarcodePage params={{SKU: '1111', ID: '2121212' }} />
);
describe('<BarcodePage />', () => {
it('render one header', () => {
expect(component.find('h1').length).toBe(1);
});
})
最佳答案
React Router 提供,并且您的代码使用 this.props.match.params
,而不是 this.props.params
。您向单元测试传递了错误的 Prop :
<BarcodePage params={{SKU: '1111', ID: '2121212' }} />
这给了你this.props.params
,但它应该是this.props.match.params
:
<BarcodePage match={{params: {SKU: '1111', ID: '2121212' }}} />
关于reactjs - 安装时 React Router v4 参数会破坏单元测试内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46687212/