I am trying to write jest to test my component.But as soon as the shallow is called my test fails by calling the fetchUsers function saying cannot read property get of null (which seems to be the initial value of myRequestor).it is not able to initialize the value of myRequestor in the MyReqUtil functional component inside MyComponent.It looks like it is not calling this function or it is not initializing the value.I am stuck in this as I am not able to write the tests everytime it just fails in the very first line where I use shallow.can anyone please help me on this.
MyComponent.jsx
let myRequestor = null;
const MyReqUtil = () => {
myRequestor = React.useContext(MyRequestorContext);
return <ApplicationLoadingOverlay isOpen backgroundStyle="clear" />;
};
class MyComponent extends React.Component {
componentDidMount() {
this.setState({ isLoading: true });
this.fetchUsers();
}
fetchUsers() {
this.setState({ isLoading: true });
const { request } = myRequestor.get({
url: '/users',
});
request
.then(({ data }) => {
if (Object.prototype.hasOwnProperty.call(data[0], 'error')) {
this.setState({
error: 'Failure', errorMsg: data[0].error, isOpen: true, isLoading: false, userItems: [{ name: 'DEFAULT', id: 'Default' }],
});
return;
}
const users = data.map(user => ({
name: user.shortName,
id: user.key,
}));
this.setState({
userItems: users, isLoading: false,
});
})
.catch((error) => {
console.log(error);
this.setState({ error: 'Failure', isOpen: true, isLoading: false });
});
}
render() {
if (this.state.tenantItems === null) {
return <MyReqUtil />;
}
}
MyComponent.test.jsx
describe('<MyComponent />', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<MyComponent />);
});
it('should check `componentDidMount()`', () => {
const instance = wrapper.instance();
jest.spyOn(instance, 'fetchUsers');
instance.componentDidMount();
expect(instance.fetchUsers).toHaveBeenCalledTimes(1);
});
it('Should Render Component Correctly', () => {
const spy = jest.spyOn(OrionReqUtil, 'fetchUsers');
const wrapper = shallow(<MyComponent />);
const instance = wrapper.instance();
spy.mockReturnValue(['mockItem1', 'mockItem2', 'mockItem3']);
});
});