gpt4 book ai didi

javascript - React-testing-library:在组件的上下文中找不到 "store"

转载 作者:行者123 更新时间:2023-12-01 17:17:57 25 4
gpt4 key购买 nike

我对测试很陌生,所以尽量保持温和!我正在尝试设置 react-testing-library,但遇到了令人困惑的错误消息:

我定义了一个自定义渲染器,其中包含我所有的提供程序,包括。还原 Provider :

import React from 'react';
import { render } from '@testing-library/react'
import { ThemeProvider } from 'styled-components';
import { defaultTheme } from 'shared/theme';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from 'reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));

const AllTheProviders = ({ children }) => {
return (
<Provider store={store}>
<ThemeProvider theme={defaultTheme}>
{children}
</ThemeProvider>
</Provider>
)
}

const customRender = (ui, options?) =>
render(ui, { wrapper: AllTheProviders, ...options })

// re-export everything
export * from '@testing-library/react'

// override render method
export { customRender as render }

但是在尝试执行测试时,我收到错误消息:

Error: Uncaught [Invariant Violation: Could not find "store" in the context of "Connect(withRouter(Header))". Either wrap the root component in a , or pass a custom React context provider to and the corresponding React context consumer to Connect(withRouter(Header)) in connect options.]



据我所知,我包括了商店。有没有解决的办法?

此问题与以下问题不重复: Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"
因为它涉及一个全局渲染器。

最佳答案

store需要模拟才能正确测试。我建议使用 redux-mock-store 库来实现这一点,但这取决于您的喜好。

在您的情况下,我会在测试文件中尝试以下内容:

import configureMockStore from 'redux-mock-store';

const mockStore = configureMockStore();
const store = mockStore({ /* here you can create a mock object for the reducer */ });

it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<Provider store={store}>
{ /* your components */ }
</Provider>, div);
ReactDOM.unmountComponentAtNode(div);
});

我希望这给你的想法和帮助!

关于javascript - React-testing-library:在组件的上下文中找不到 "store",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60772986/

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