React Jest test无法读取未定义

时间:2017-07-24 18:46:38

标签: javascript reactjs testing jestjs

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

enter image description here

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()
        }
    }

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);
  });
});

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

1 个答案:

答案 0 :(得分:3)

看起来你可能会遇到一些错误,一个是在你的测试中你没有传递任何道具。

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

请参阅您的if声明,但我会在此处明确说明

if (R.isEmpty(props.view)) {
   isViewServices(this.state.location)
     ? props.gotoServicesView()
     : props.gotoUsersView()
}

在Main.test

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