问题描述
我有一个组件Demo,其Label取决于redux-form状态下字段的当前值.我正在使用formValueSelector从表单状态获取"param"字段的当前值.它工作正常.但是,在运行npm test时,选择器函数始终返回undefined.我该如何嘲笑它?
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.
我有一个类似
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>
);
}
}导出默认样本;
并且,测试代码就像
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();
});
});
推荐答案
您没有为formValueSelector提供针对选择器期望状态的适当模拟.
You aren't providing the formValueSelector with an adequate mock for the state that the selector expects.
解决方案:选择器期望redux提供的全局状态对象.当前的嘲笑状态并不反映这一点.将模拟物更改为期望的形状可解决此问题:
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:
它是这样的形状:
{
form: {
sampleform: {
values: {
keyOfState: "Label"
}
}
}
}
注意:存储在sampleform键上的对象包含更多条目,但与模拟无关.
Note: the object stored at the sampleform key includes more entries, but they are irrelevant for the mock.
这里是解决您问题的复制品的链接: https://github.com/mjsisley/reduxFormMockIssue
Here is a link to a reproduction that resolves your issue:https://github.com/mjsisley/reduxFormMockIssue
请注意:我是由马特·洛(Matt Lowe)指挥的.我是与他一起从事其他多个项目的开发人员.
Please note: I was directed here by Matt Lowe. I am the developer that has worked with him on a number of other projects.
这篇关于Redux-Form:如何在Jest中模拟formValueSelector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!