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