I was asked to implement a solution that allows to dispatch multiple actions with a single dispatch. Here’s the solution I developed:
The action:
export const batchActions = <T extends unknown[]>(actions: Action<T[number]>[]): { type: string; meta: { batch: true }; payload: Action<T[number]>[] } => {
return { type: BATCH, meta: { batch: true }, payload: actions }
}
The middleware:
const batchDispatchMiddleware = <T extends string, P>(): Middleware => {
return (store) => (next) => (action: unknown) => {
const typeAction= action as Action<T, P>
if (!typeAction.meta?.batch) return next(action)
return (typeAction.payload as Action<T, P>[]).map((action) => store.dispatch(action))
}
}
The solution works fine, however our Jest tests fails to assert some cases. E.g. via this action we update reducers, which shows elements on the screen:
dispatch(batchActions([showHeader(), showLogoutButtonInHeader()]))
After using this solution the test cannot find them on the screen.
renderWithProviders(
<ExampleContainer />
)
//await waitFor(()=>screen.queryByTestId(dataTestId.moduleHeaderTitle)) <-tried, but no luck
expect(screen.getByTestId('header')).toBeInTheDocument()<-fails
expect(showHeaderSpy).toBeCalledTimes(1)<-works
The application is functioning correctly. We can see the header and button on the screen. However, we’re having trouble using Jest to locate them and verify their presence in the document.