Search code examples
reactjsjestjsredux-formspyreact-redux-form

Redux-Form : How to mock formValueSelector in Jest


I have a component Demo whose Label depends on the current value of a field in the redux-form state. I am using formValueSelector to get the current value of "param" field from the form state. It works fine. However, while running npm test, the selector function always returns undefined. How can I mock it?

Please let me know if I am doing this in a wrong way.

I have a component like

class Sample extends React.Component {
render() {
    const {param, state} = this.props;
    const selector = formValueSelector('sampleform');
    return (
        <div>
            <Demo
                name="name"
                label={selector(state, `${param}`)}
            />
        </div>
    );
}

} export default Sample;

and, testing code is like

function setup() {
    const spy = jest.fn();
    const store = createStore(() => ({}));
    const Decorated = reduxForm({ form: 'sampleform' })(Sample);

    const props = {
        "param":"keyOfState",
        "state":{"keyOfState":"Label"}
    }
    const mockedComponent = <Provider store={store}>
        <MuiThemeProvider muiTheme={MuiStyles()}>
            <Decorated {...props}>
                <span></span>
            </Decorated>
        </MuiThemeProvider>
    </Provider>;
    return {
        props,
        mockedComponent}
}
describe('Sample Component', () => {
    it('should render the snapshot', () => {
        const { mockedComponent } = setup()
        const tree = renderer.create(
            mockedComponent
        ).toJSON();
        expect(tree).toMatchSnapshot();
    });
});

Solution

  • You aren't providing the formValueSelector with an adequate mock for the state that the selector expects.

    Solution: The selector expects the global state object provided by redux. The current mocked state doesn't reflect this. Changing the mock to the shape expected fixes the issue:

    It is of this shape:

    {
      form: {
        sampleform: {
          values: {
            keyOfState: "Label"
          }
        }
      }
    }
    

    Note: the object stored at the sampleform key includes more entries, but they are irrelevant for the mock.

    Here is a link to a reproduction that resolves your issue:https://github.com/mjsisley/reduxFormMockIssue

    Please note: I was directed here by Matt Lowe. I am the developer that has worked with him on a number of other projects.