reactjs - Enzyme:如何测试容器组件的 props 变化?
问题描述
为了渲染连接到 redux 存储的容器组件,我使用这个函数来渲染组件
function render(Component, props, storeData) {
const mockStore = configureStore([thunkMiddleware]);
const store = mockStore(storeData);
return mount(
<Provider store={store}>
<Component {...props} />
</Provider>
);
}
现在,我需要测试渲染的组件的 props 更改,但它看起来ReactWrapper.setProps
只适用于 Root 组件。
MyComponent
是一个容器组件,它使用connect
.
describe('MyComponent', () => {
it('should work at props change', () => {
const wrapper = render(MyComponent, { value: 1 }, initialStoreValue);
wrapper.find(MyComponent).setProps({ value: 2});
// then expect something.
});
});
解决方案
有几点需要考虑:
redux-mock-store
允许将函数作为状态源传递 -redux-mock-store
每次都会调用该函数- 触发重新渲染组件,
useSelector
或者connect()
我们可以dispatch()
使用任何动作类型。从字面上看。 - 我们需要将更新存储包装到
act()
,否则它可能无法正常工作,并且肯定会抱怨console.error
.
所以记住这一点,我们可以增强render
:
function render(Component, props, initialStoreData) {
let currentStoreData = initialStoreData;
const mockStore = configureStore([thunkMiddleware]);
const store = mockStore(() => currentStoreData);
const wrapper = mount(
<Provider store={store}>
<Component {...props} />
</Provider>
);
const updateStore = (newStoreData) => {
currentStoreData = newStoreData;
act(() => {
store.dispatch({ type: '' }); // just to trigger re-rendering components
});
}
return { wrapper, updateStore };
}
然后在测试中:
describe('MyComponent', () => {
it('does something when store changes somehow', () => {
const { wrapper, updateStore } = render(MyComponent, { value: 1 }, initialStoreValue);
updateStore({ someReduxValue: 2});
// then expect something.
});
});
推荐阅读
- merge - ffmpeg 合并 mxf 音频和 m2v 视频
- java - 如何在三元运算符中进行转换?
- angular - 如何在 NG-Zorro 中更改 nz-table 的样式
- scala - Play 应用程序类的含义
- android - ViewModel 没有显示任何内容
- excel - 代码已正确执行时陷入循环
- macos - 在 macOS Mojave 中增加 HNPROC
- angular - Angular:如何在来自另一个组件的递归组件的所有子组件中运行一个函数?
- ruby-on-rails - Rails 的 localhost :“缺少请求格式的模板”?
- mysql - mysql中Rails的类似沙盒的功能