我有一个简单的 Todo 组件,它利用了我正在使用酶测试的 react-redux 钩子,但我得到一个错误或一个带有浅渲染的空对象,如下所述。
使用 react-redux 的钩子测试组件的正确方法是什么?
Todos.js
const Todos = () => {
const { todos } = useSelector(state => state);
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
};
Todos.test.js v1
...
it('renders without crashing', () => {
const wrapper = shallow(<Todos />);
expect(wrapper).toMatchSnapshot();
});
it('should render a ul', () => {
const wrapper = shallow(<Todos />);
expect(wrapper.find('ul').length).toBe(1);
});
v1 错误:
...
Invariant Violation: could not find react-redux context value;
please ensure the component is wrapped in a <Provider>
...
Todos.test.js v2
...
// imported Provider from react-redux
it('renders without crashing', () => {
const wrapper = shallow(
<Provider store={store}>
<Todos />
</Provider>,
);
expect(wrapper).toMatchSnapshot();
});
it('should render a ul', () => {
const wrapper = shallow(<Provider store={store}><Todos /></Provider>);
expect(wrapper.find('ul').length).toBe(1);
});
v2 tests also fail since wrapper
is the <Provider>
and calling dive()
on wrapper
will return the same error as v1.
在此先感谢您的帮助!
原文由 crowns4days 发布,翻译遵循 CC BY-SA 4.0 许可协议
我可以使用酶安装工具测试使用 redux 钩子的组件,并向 Provider 提供模拟存储:
零件
测试