小编cro*_*ays的帖子

如何使用react-redux挂钩测试组件?

我有一个简单的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>
  );
};
Run Code Online (Sandbox Code Playgroud)

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);
});
Run Code Online (Sandbox Code Playgroud)

v1错误:

...
Invariant Violation: could not find react-redux context value; 
please ensure the component is wrapped in a <Provider>
...
Run Code Online (Sandbox Code Playgroud)

Todos.test.js …

testing reactjs redux enzyme react-redux

14
推荐指数
5
解决办法
3908
查看次数

标签 统计

enzyme ×1

react-redux ×1

reactjs ×1

redux ×1

testing ×1