在这个更新后的示例中,我们使用 configureStore 函数来创建 Redux store。我们将 rootReducer 传递给了 configureStore 的 reducer 选项,并通过 preloadedState 选项传递了初始状态。这样,我们就创建了一个符合 Redux Toolkit 推荐的 Redux store。
js 代码解读复制代码
import React from ‘react‘;
import { render, screen } from ‘@testing-library/react‘;
import { Provider } from ‘react-redux‘;
import { configureStore } from ‘@reduxjs/toolkit‘;
import TodoList from ‘./TodoList‘; // 待测试组件
import rootReducer from ‘./reducers‘; // 我们的 root reducer
// 使用模拟的 Redux Provider
const renderWithRedux = (
component,
{ initialState, store = configureStore({ reducer: rootReducer,
preloadedState: initialState }) } = {}
) => {
return {
…render(<Provider store={store}>{component}</Provider>),
store,
};
};
describe(‘TodoList‘, () => {
test(‘renders todo items‘, () => {
const initialState = {
todos: [{ id: 1, text: ‘Buy groceries‘, completed: false }],
};
const { getByText } = renderWithRedux(<TodoList />, { initialState });
expect(getByText(‘Buy groceries‘)).toBeInTheDocument();
});
});