Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

473
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda