thunkTester.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import configureMockStore from 'redux-mock-store';
  2. import thunk from 'redux-thunk';
  3. import { ActionOf } from 'app/core/redux/actionCreatorFactory';
  4. const mockStore = configureMockStore([thunk]);
  5. export interface ThunkGiven {
  6. givenThunk: (thunkFunction: any) => ThunkWhen;
  7. }
  8. export interface ThunkWhen {
  9. whenThunkIsDispatched: (...args: any) => ThunkThen;
  10. }
  11. export interface ThunkThen {
  12. thenDispatchedActionsEqual: (actions: Array<ActionOf<any>>) => ThunkWhen;
  13. thenDispatchedActionsAreEqual: (callback: (actions: Array<ActionOf<any>>) => boolean) => ThunkWhen;
  14. thenThereAreNoDispatchedActions: () => ThunkWhen;
  15. }
  16. export const thunkTester = (initialState: any): ThunkGiven => {
  17. const store = mockStore(initialState);
  18. let thunkUnderTest = null;
  19. const givenThunk = (thunkFunction: any): ThunkWhen => {
  20. thunkUnderTest = thunkFunction;
  21. return instance;
  22. };
  23. function whenThunkIsDispatched(...args: any): ThunkThen {
  24. store.dispatch(thunkUnderTest(...arguments));
  25. return instance;
  26. }
  27. const thenDispatchedActionsEqual = (actions: Array<ActionOf<any>>): ThunkWhen => {
  28. const resultingActions = store.getActions();
  29. expect(resultingActions).toEqual(actions);
  30. return instance;
  31. };
  32. const thenDispatchedActionsAreEqual = (callback: (dispathedActions: Array<ActionOf<any>>) => boolean): ThunkWhen => {
  33. const resultingActions = store.getActions();
  34. expect(callback(resultingActions)).toBe(true);
  35. return instance;
  36. };
  37. const thenThereAreNoDispatchedActions = () => {
  38. return thenDispatchedActionsEqual([]);
  39. };
  40. const instance = {
  41. givenThunk,
  42. whenThunkIsDispatched,
  43. thenDispatchedActionsEqual,
  44. thenDispatchedActionsAreEqual,
  45. thenThereAreNoDispatchedActions,
  46. };
  47. return instance;
  48. };