DEV Community

Dennis Zhang
Dennis Zhang

Posted on • Edited on

jest测试redux需要根组件

在这个更新后的示例中,我们使用 configureStore 函数来创建 Redux store。我们将 rootReducer 传递给了 configureStore 的 reducer 选项,并通过 preloadedState 选项传递了初始状态。这样,我们就创建了一个符合 Redux Toolkit 推荐的 Redux store。
js 代码解读复制代码

// TodoList.test.js
import React from 'react';
import { render, screen,fireEvent } 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, //  是一个对象{a: aReducer,b:bReducer}
      preloadedState: initialState,
    }),
  } = {}
) => {
  return {
    ...render(<Provider store={store}>{component}</Provider>),
    store,
  };
};

describe('TodoList', () => {
  test('renders todo items',async () => {
    const initialState = {
      todos: [{ id: 1, text: 'Buy groceries', completed: false }],
    };
    const props={}
    const { getByText,store } = renderWithRedux(<TodoList {...props}/>, { initialState });
    store.dispatch(action(['xxx]))
    await waitFor(()=>{
     expert(screen.getByRole('row')).toBeInTheDocument()
     expect(getByText('Buy groceries')).toBeInTheDocument();
     fireEvent(screen.getByRole('row')).click()
    })

  });
});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)