在使用 react-testing-library
和 Redux
进行组件测试时,如果在 Connect(Currency)
的上下文中找不到 store
,通常是因为测试环境中没有正确设置 Redux 的 store
。以下是一些基础概念和相关解决方案:
store
,它保存了整个应用的状态。所有组件通过 connect
函数连接到 store
,从而获取所需的状态和分发操作。connect
函数,用于将 React 组件与 Redux store
连接起来。以下是一个示例,展示如何在测试环境中设置 Redux store
并使用 react-testing-library
进行测试:
import React from 'react';
import { render, screen } from '@testing-library/react';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
import ConnectedCurrency from './ConnectedCurrency'; // 假设这是你的组件
const mockStore = configureStore([]);
describe('ConnectedCurrency', () => {
let store;
beforeEach(() => {
// 初始化 store 并填充一些状态
store = mockStore({
currency: {
rate: 1.2,
name: 'USD',
},
});
});
it('should render with correct currency name', () => {
render(
<Provider store={store}>
<ConnectedCurrency />
</Provider>
);
expect(screen.getByText('USD')).toBeInTheDocument();
});
});
store
: 如果在测试中没有使用 <Provider store={store}>
包裹组件,Redux store
将无法传递到组件树中。<Provider>
: 在测试文件中使用 <Provider store={store}>
包裹被测试的组件。redux-mock-store
的中间件功能来模拟异步操作,如 API 调用。通过上述方法,可以确保在测试环境中正确设置和使用 Redux store
,从而避免找不到 store
的问题。
领取专属 10元无门槛券
手把手带您无忧上云