bill
bill

Reputation: 318

mapDispatchToProps props null in jest test

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();
  });
});

Upvotes: 1

Views: 1609

Answers (1)

Misha
Misha

Reputation: 6588

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();)

Upvotes: 2

Related Questions