我有一个简单的 Todo 组件,它利用了我正在使用 enzyme 进行测试的 react-redux Hook ,但我收到了一个错误或一个带有浅渲染的空对象,如下所述。
使用 react-redux 的钩子(Hook)测试组件的正确方法是什么?
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);
});
自 wrapper
以来,v2 测试也失败了是 <Provider>
并调用 dive()
在 wrapper
将返回与 v1 相同的错误。
最佳答案
模拟 useSelector 使用可以做到这一点
import * as redux from 'react-redux'
const spy = jest.spyOn(redux, 'useSelector')
spy.mockReturnValue({ username:'test' })
关于reactjs - 如何使用带有 Enzyme 的 react-redux hooks 测试组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56827300/