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

Sign up to request clarification or add additional context in comments.

4 Comments

What's the merge function here?
Also what should the initialState be? A state for one, or all reducers?
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
Ok, that makes sense. Thanks!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.