首页 > 解决方案 > redux/react-testing-library 的初始状态对于下一个测试用例保持不变

问题描述

这是我的测试文件

describe("Header", () => {
  // passed
  it("should render a public header when the user is not authorized", () => {
    render(<Header />, {
      initialState: {
        user: { authorized: false },
      },
    });

    expect(screen.getByTestId("private-header")).toBeInTheDocument();
  });

  // failed
  it("should render a private header when the user is authorized", () => {
    render(<Header />, {
      initialState: {
        user: { authorized: true },
      },
    });

    expect(screen.getByTestId("public-header")).toBeInTheDocument();
  });
});

对于第二个测试用例,authorized值为false。但我假设它等于true. 在第一个测试用例之后,初始状态保持不变。

这是我的 test-utils.js 文件

import { render as testingLibraryRender } from "@testing-library/react";
import { Provider } from "react-redux";
import { MemoryRouter } from "react-router-dom";
import configureStore from "../redux/store";

const customRender = (
  ui,
  { initialState, store = configureStore(initialState), ...renderOptions } = {}
) => {
  // All necessary providers for rendering components
  const AllTheProviders = ({ children }) => (
    <Provider store={store}>
      <MemoryRouter>{children}</MemoryRouter>
    </Provider>
  );

  return testingLibraryRender(ui, { wrapper: AllTheProviders, ...renderOptions });
};

// Re-export everything from testing-library
export * from "@testing-library/react";

// Override render from testing-library with custom render
export { customRender as render };

这是我的 store.js 文件

import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
import { setSizes } from '../actions/common/actions';

let store;

window.addEventListener('resize', () => {
  if (store) {
    store.dispatch(setSizes({
      width: window.innerWidth,
      height: window.innerHeight,
    }));
  }
}, { passive: true });

export function configureStore(initialState) {
  const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
  store = store || createStore(
    rootReducer,
    initialState,
    composeEnhancers(
      applyMiddleware(thunk),
    ),
  );

  return store;
}

export default configureStore;

标签: reactjsreduxreact-reduxjestjsreact-testing-library

解决方案


想通了,我在两个测试中使用相同的商店实例,而不是每次都创建一个新商店。


推荐阅读