useStatelessReducer.test.tsx 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { renderHook } from '@testing-library/react-hooks';
  2. import React, { PropsWithChildren } from 'react';
  3. import { useStatelessReducer, useDispatch, DispatchContext, combineReducers } from './useStatelessReducer';
  4. describe('useStatelessReducer Hook', () => {
  5. it('When dispatch is called, it should call the provided reducer with the correct action and state', () => {
  6. const action = { type: 'SOME ACTION' };
  7. const reducer = jest.fn();
  8. const state = { someProp: 'some state' };
  9. const { result } = renderHook(() => useStatelessReducer(() => {}, state, reducer));
  10. result.current(action);
  11. expect(reducer).toHaveBeenCalledWith(state, action);
  12. });
  13. it('When an action is dispatched, it should call the provided onChange callback with the result from the reducer', () => {
  14. const action = { type: 'SOME ACTION' };
  15. const state = { propA: 'A', propB: 'B' };
  16. const expectedState = { ...state, propB: 'Changed' };
  17. const reducer = () => expectedState;
  18. const onChange = jest.fn();
  19. const { result } = renderHook(() => useStatelessReducer(onChange, state, reducer));
  20. result.current(action);
  21. expect(onChange).toHaveBeenLastCalledWith(expectedState);
  22. });
  23. });
  24. describe('useDispatch Hook', () => {
  25. it('Should throw when used outside of DispatchContext', () => {
  26. const { result } = renderHook(() => useDispatch());
  27. expect(result.error).toBeTruthy();
  28. });
  29. it('Should return a dispatch function', () => {
  30. const dispatch = jest.fn();
  31. const wrapper = ({ children }: PropsWithChildren<{}>) => (
  32. <DispatchContext.Provider value={dispatch}>{children}</DispatchContext.Provider>
  33. );
  34. const { result } = renderHook(() => useDispatch(), {
  35. wrapper,
  36. });
  37. expect(result.current).toBe(dispatch);
  38. });
  39. });
  40. describe('combineReducers', () => {
  41. it('Should correctly combine reducers', () => {
  42. const reducerA = jest.fn();
  43. const reducerB = jest.fn();
  44. const combinedReducer = combineReducers({ reducerA, reducerB });
  45. const action = { type: 'SOME ACTION' };
  46. const initialState = { reducerA: 'A', reducerB: 'B' };
  47. combinedReducer(initialState, action);
  48. expect(reducerA).toHaveBeenCalledWith(initialState.reducerA, action);
  49. expect(reducerB).toHaveBeenCalledWith(initialState.reducerB, action);
  50. });
  51. });