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
Advertisement
Answer
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