0

I have a component like this:

export const DetailsItem: FC = (): ReactElement => {
  const { isInEditMode } = useAppSelector(({ editMode }) => editMode);
  if (isInEditMode) {
    return <DetailsItemEdit />;
  }
  return <DetailsItemDisplay />;
};

and am trying to test it.

describe('DetailsItem', () => {
  it('should render DetailsItemDisplay component', () => {
    render(
      <Provider store={}> // I want to pass isInEditMode here.
        <DetailsItem />
      </Provider>,
    );

    screen.debug();
  });
});

The problem is, I somehow need to mock the store, to match my case. Any ideas how I should handle this?

I remember in my previous project I used a npm package to do this, but can't find it now, and can't remember how I did it, or what it was called

1 Answer 1

1

you can create a helper function for your tests to abstract the setup of the store/dependencies:

// import dependencies here:

function createTestWithStore(stateFromTest, component) {
  let reducer = { reducerA, reducerB };
  let preloadedState = merge(initialState, stateFromTest);
  let store = configureStore({
    reducer,
    preloadedState
  })
  return <Provider store={store}>{component}</Provider>
}

and use it in your tests:

describe('DetailsItem', () => {
  it('should render DetailsItemDisplay component with a single item', () => {
    let testState = { list: [{ id: 1, name: "John" }] };
    render(createTestWithStore(testState, <DetailsItem />));
    screen.debug();
  });

  it('should render DetailsItemDisplay component no item', () => {
    let testState = { list: [] };
    render(createTestWithStore(testState, <DetailsItem />));
    screen.debug();
  });
});

have a look in the "Writing Tests" page from Redux, it is part of the "Recommended practices for testing apps using Redux": https://redux.js.org/usage/writing-tests#connected-components

4
  • What's the merge function here? Commented Sep 6, 2021 at 11:51
  • Also what should the initialState be? A state for one, or all reducers? Commented Sep 6, 2021 at 11:52
  • 1
    that's up to you to decide based on your application state... my personal approach is to setup all reducers on tests... the "merge" function there is to illustrate merging a default state with state from tests, you can use any solution that you want... the main ideia and benefit of creating test functions like that is maintainability in long term Commented Sep 6, 2021 at 12:40
  • Ok, that makes sense. Thanks! Commented Sep 6, 2021 at 12:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.