test-utils.tsx 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // See https://redux.js.org/usage/writing-tests#setting-up-a-reusable-test-render-function for more information
  2. import React, { PropsWithChildren } from "react";
  3. import { Provider } from "react-redux";
  4. import { configureStore } from "@reduxjs/toolkit";
  5. // eslint-disable-next-line import/no-extraneous-dependencies
  6. import { RenderOptions, render } from "@testing-library/react";
  7. import { AppStore, RootState, rootReducer } from "./src/store";
  8. const setupStore = (preloadedState?: Partial<RootState>): AppStore =>
  9. configureStore({
  10. reducer: rootReducer,
  11. preloadedState,
  12. });
  13. // This type interface extends the default options for render from RTL, as well
  14. // as allows the user to specify other things such as initialState, store.
  15. interface ExtendedRenderOptions extends Omit<RenderOptions, "queries"> {
  16. preloadedState?: Partial<RootState>;
  17. store?: AppStore;
  18. }
  19. // Export our own customized renderWithProviders function that creates a new Redux store and renders a <Provider>
  20. // Note that this creates a separate Redux store instance for every test, rather than reusing the same store instance and resetting its state
  21. export function renderWithProviders(
  22. ui: React.ReactElement,
  23. {
  24. preloadedState = {},
  25. // Automatically create a store instance if no store was passed in
  26. store = setupStore(preloadedState),
  27. ...renderOptions
  28. }: ExtendedRenderOptions = {},
  29. ) {
  30. function Wrapper({ children }: PropsWithChildren<object>): JSX.Element {
  31. return <Provider store={store}>{children}</Provider>;
  32. }
  33. return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) };
  34. }