React Jest test无法读取undefined的属性'pathname'

Leo*_*ban 6 javascript testing reactjs jestjs

不知道为什么我在我的简单Main.test文件中收到此错误.

在此输入图像描述

Main.js的构造函数

export class Main extends Component {
    constructor(props) {
        super(props);

        this.state = {
            location: splitString(props.location.pathname, '/dashboard/')
        }

        if (R.isEmpty(props.view)) {
            isViewServices(this.state.location)
                ? this.props.gotoServicesView()
                : this.props.gotoUsersView()
        }
    }
Run Code Online (Sandbox Code Playgroud)

Main.test的

import React from 'react'
import * as enzyme from 'enzyme'
import toJson from 'enzyme-to-json'
import { Main } from './Main'
import Sidebar from '../../components/Common/sidebar'

const main = enzyme.shallow(<Main />);

describe('<Main /> component', () => {

  it('should render', () => {
    const tree = toJson(main);
    expect(tree).toMatchSnapshot();
  });

  it('contains the Sidebar', () => {
    expect(main.find(Sidebar).length).toBe(1);
  });
});
Run Code Online (Sandbox Code Playgroud)

有没有办法模拟'路径名'?

enj*_*ife 5

似乎您可能有一些错误,其中一个是在您的测试中没有传递任何道具。

另一个来自您this.props在构造函数中访问。

请参阅您的if声明,但我会将修复程序放在这里是明确的

if (R.isEmpty(props.view)) {
   isViewServices(this.state.location)
     ? props.gotoServicesView()
     : props.gotoUsersView()
}
Run Code Online (Sandbox Code Playgroud)

在 Main.test

const location = { pathname: '/dashboard/' };
const main = enzyme.shallow(<Main location={ location }/>);
Run Code Online (Sandbox Code Playgroud)