最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Jest test Cannot read property 'pathname' of undefined - Stack Overflow

programmeradmin6浏览0评论

Not sure why I'm getting this error in my simple Main.test file.

The constructor of 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 '../../ponents/Common/sidebar'

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

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

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

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

Is there a way to mock up the 'pathname'?

Not sure why I'm getting this error in my simple Main.test file.

The constructor of 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 '../../ponents/Common/sidebar'

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

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

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

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

Is there a way to mock up the 'pathname'?

Share Improve this question asked Jul 24, 2017 at 18:46 Leon GabanLeon Gaban 39.1k122 gold badges349 silver badges550 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

It seems you might have a few errors one being that in your test your not passing in any props.

And another from you accessing this.props in your constructor.

See your if statement but I'll put the fix here to be explicit

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

In Main.test

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

评论列表(0)

  1. 暂无评论