1
votes

I have just started my first react job (yay!) and am attempting to write unit tests using jest. i am having an issue with mapDispatchToProps in my test.

please note, the test passes, but it is throwing the following error message:

Warning: Failed prop type: The prop testDispatch is marked as required in TestJest, but its value is undefined in TestJest

error seems to be test related to the test as it is not thrown when running the page in the web browser. also, mapStateToProps works fine, included to show it works.

using enzyme/shallow in order not to interact with the <Child/> component.

testJest.js

import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import Child from './Child'

export class TestJest extends React.Component {
  render() {
    return (<div>ABC - <Child /></div>);
  }
}

TestJest.propTypes = {
  testDispatch: PropTypes.func.isRequired,
  testState: PropTypes.arrayOf(PropTypes.string)
};

const mapStateToProps = (state) => {
  return {
    testState: state.utilization.pets    // ['dog','cat']
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    testDispatch: () => dispatch({'a' : 'abc'})
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(TestJest);

testJest-test.js

import React from 'react';
import { TestJest } from '../Components/testJest';
import TestJestSub2 from '../Components/TestJestSub2';
import { shallow } from 'enzyme';

describe('TESTJEST', () => {
  it('matches snapshot', () => {
    const wrapper = shallow(<TestJest />);
    expect(wrapper).toMatchSnapshot();
  });
});
1
It's because you call <TestJest /> in your test without testDispatch nor testState (you set them as required in your propTypes) ?soywod
@soywod - thank you for your reply. i do not yet know enough about react/jest to respond fully to your comment, so let me add two things which may be relevant: 1) the testState requirement passes, it is only testDispatch that fails, and 2) this is how the component gets called in the app and does not generate any error messages. thanks again for taking the time to reply. this may also address your concern: testState and testDispatch are injected into <TestJest /> via connect().bill

1 Answers

2
votes

You can pass empty function to TestJest as testDispatch prop:

it('matches snapshot', () => {
  const wrapper = shallow(<TestJest testDispatch={() => {}} />);
  expect(wrapper).toMatchSnapshot();
});

or pass jest mock function:

it('matches snapshot', () => {
  const wrapper = shallow(<TestJest testDispatch={jest.fn()} />);
  expect(wrapper).toMatchSnapshot();
});

if you want to check if testDispatch was called (expect(wrapper.instance().props.testDispatch).toBeCalled();)