Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

474
Views
How to use shallow in React Jest unittest to avoid getting 'TypeError: Cannot read properties of undefined (reading state)' error?

I am trying to test a react class component which has a props.location (coming from React-router) in the componentDidMount function. When, I am trying to test it with react enzyme library using shallow method, I am getting below error:

'TypeError: Cannot read properties of undefined (reading state)'

Including the relevant parts of the code here :
Router.js

import {BrowseRouter as Router, Switch , Route} from 'react-router-dom';
  function Routes() {
       return (
       <Router>
          <Switch>
              <Route path="/" exact render={(props) => <MyPage {...props} />}/>
              <Route path="/loadfile" component={loadfile}/>
                       
          </Switch>
        </Router>
       )
  }
        
export default Routes;

MyPage.js

 class MyPage extends React.Component {
        
     constructor(props) {
        super(props);
        this.state = {
          isClicked:0
        };
      }
      componentDidMount(props) {
         if(this.props.location.state != undefined ) {
             this.setState({isClicked:1});
         }
      }
      render() {
         return (
            <div>
              <Button id="click-this-btn'>Click this</Button>
              
            </div>
         ); 
      }
   }
 export default MyPage; 

MyPage.test.js

import React from 'react';
import{render, screen} from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import Adapter from 'enzyme-adapter-react-16';
import {shallow, mount , configure} from 'enzyme';
import MyPage from '../MyPage';

configure({adapter: new Adapter()}); 
describe('testing button' , () => {
  let wrapper;
  beforeEach(() => {
     wrapper = shallow(<MyPage></MyPage>);
   }
   
  describe('click button test' , () => {
   it('test the button' , () => {
       wrapper.instance().componentDidMount();
       expect(wrapper.find("#click-this-btn").text()).toBe("Click this");
   });
   
  });
});

How should I write the Jest test to get rid of the TypeError ? Please help. Thanks

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!