Redux-Form : How to mock formValueSelector in Jest

心已入冬 提交于 2019-12-14 03:57:49

问题


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

回答1:


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.




回答2:


For anyone in the future - if for some reason you actually need to mock FormValueSelector, I just exported a wrapper for it from my Helpers module:

export const tableTypeSelector = formValueSelector('toggle')

and then mocked that:

import * as Helpers from 'helpers'
...
stub = sinon.stub(Helpers, 'tableTypeSelector').returns('charges')


来源:https://stackoverflow.com/questions/46433323/redux-form-how-to-mock-formvalueselector-in-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!