安装时 React Router v4 参数在单元测试中破坏

Jim*_*imi 3 reactjs jestjs enzyme

我有一个带有 URL 参数的 React 组件。当我运行测试并安装组件时,参数始终未定义,因此会中断测试。我试图将它们硬编码为常量、道具,但仍然无法正常工作。我可以尝试其他任何想法吗?

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);
  });
})
Run Code Online (Sandbox Code Playgroud)

Li3*_*357 5

React Router 提供并且您的代码使用this.props.match.params,而不是this.props.params. 您将错误的道具传递给单元测试:

<BarcodePage params={{SKU: '1111', ID: '2121212' }} />
Run Code Online (Sandbox Code Playgroud)

这给了你this.props.params,但它应该是this.props.match.params

<BarcodePage match={{params: {SKU: '1111', ID: '2121212' }}} />
Run Code Online (Sandbox Code Playgroud)