thunkTester.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // @ts-ignore
  2. import { PayloadAction } from '@reduxjs/toolkit';
  3. import configureMockStore from 'redux-mock-store';
  4. import thunk from 'redux-thunk';
  5. const mockStore = configureMockStore([thunk]);
  6. export interface ThunkGiven {
  7. givenThunk: (thunkFunction: any) => ThunkWhen;
  8. }
  9. export interface ThunkWhen {
  10. whenThunkIsDispatched: (...args: any) => Promise<Array<PayloadAction<any>>>;
  11. }
  12. export const thunkTester = (initialState: any, debug?: boolean): ThunkGiven => {
  13. const store = mockStore(initialState);
  14. let thunkUnderTest: any = null;
  15. let dispatchedActions: Array<PayloadAction<any>> = [];
  16. const givenThunk = (thunkFunction: any): ThunkWhen => {
  17. thunkUnderTest = thunkFunction;
  18. return instance;
  19. };
  20. const whenThunkIsDispatched = async (...args: any): Promise<Array<PayloadAction<any>>> => {
  21. await store.dispatch(thunkUnderTest(...args));
  22. dispatchedActions = store.getActions();
  23. if (debug) {
  24. console.log('resultingActions:', JSON.stringify(dispatchedActions, null, 2));
  25. }
  26. return dispatchedActions;
  27. };
  28. const instance = {
  29. givenThunk,
  30. whenThunkIsDispatched,
  31. };
  32. return instance;
  33. };