gpt4 book ai didi

reactjs - 如何使用带有 Enzyme 的 react-redux hooks 测试组件?

转载 作者:行者123 更新时间:2023-11-28 19:40:10 25 4
gpt4 key购买 nike

我有一个简单的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com