reducerTester.test.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { createAction } from '@reduxjs/toolkit';
  2. import { AnyAction } from 'redux';
  3. import { reducerTester } from './reducerTester';
  4. interface DummyState {
  5. data: string[];
  6. }
  7. const initialState: DummyState = {
  8. data: [],
  9. };
  10. const dummyAction = createAction<string>('dummyAction');
  11. const mutatingReducer = (state: DummyState = initialState, action: AnyAction): DummyState => {
  12. if (dummyAction.match(action)) {
  13. state.data.push(action.payload);
  14. return state;
  15. }
  16. return state;
  17. };
  18. const okReducer = (state: DummyState = initialState, action: AnyAction): DummyState => {
  19. if (dummyAction.match(action)) {
  20. return {
  21. ...state,
  22. data: state.data.concat(action.payload),
  23. };
  24. }
  25. return state;
  26. };
  27. describe('reducerTester', () => {
  28. describe('when reducer mutates state', () => {
  29. it('then it should throw', () => {
  30. expect(() => {
  31. reducerTester<DummyState>()
  32. .givenReducer(mutatingReducer, initialState)
  33. .whenActionIsDispatched(dummyAction('some string'));
  34. }).toThrow();
  35. });
  36. });
  37. describe('when reducer does not mutate state', () => {
  38. it('then it should not throw', () => {
  39. expect(() => {
  40. reducerTester<DummyState>()
  41. .givenReducer(okReducer, initialState)
  42. .whenActionIsDispatched(dummyAction('some string'));
  43. }).not.toThrow();
  44. });
  45. });
  46. });