Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Jest test Cannot read property 'pathname' of undefined

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

enter image description here

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 '../../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);
  });
});

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

like image 202
Leon Gaban Avatar asked Jul 24 '17 18:07

Leon Gaban


People also ask

How install NPM React router?

To install React Router, all you have to do is run npm install react-router-dom@6 in your project terminal and then wait for the installation to complete. If you are using yarn then use this command: yarn add react-router-dom@6 .

What is the difference between React-router-Dom and React router?

react-router is the core package containing standard components and functionalities to implement routing in React applications. On the other hand, react-router-dom is a specialized package that you can use only in web-browser-based application development.


1 Answers

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 }/>);
like image 129
enjoylife Avatar answered Sep 26 '22 03:09

enjoylife