useShadowedState.test.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { renderHook, act } from '@testing-library/react-hooks';
  2. import { useShadowedState } from './useShadowedState';
  3. describe('useShadowedState', () => {
  4. it('should handle outside changes', () => {
  5. const { result, rerender } = renderHook(({ outsideVal }) => useShadowedState(outsideVal), {
  6. initialProps: { outsideVal: '42' },
  7. });
  8. // first we verify it has the initial value
  9. expect(result.current[0]).toBe('42');
  10. // then we change it
  11. act(() => {
  12. result.current[1]('53');
  13. });
  14. // and verify it has the changed value
  15. expect(result.current[0]).toBe('53');
  16. // then we change the value from the outside
  17. rerender({ outsideVal: '71' });
  18. // and verify the now has the value from the outside
  19. expect(result.current[0]).toBe('71');
  20. });
  21. it('should handle changs applied from inside to outside', () => {
  22. // this is a test-case created because of a bug that was
  23. // found with this component, it happens when:
  24. // 1. the value is changed inside
  25. // 2. the inside-value gets applied to the outside-component,
  26. // so now the outside-value again matches the inside-value
  27. // 3. the value changes again inside
  28. // at this point the value should be correct.
  29. const { result, rerender } = renderHook(({ outsideVal }) => useShadowedState(outsideVal), {
  30. initialProps: { outsideVal: '1' },
  31. });
  32. // first we verify it has the initial value
  33. expect(result.current[0]).toBe('1');
  34. // then we change it
  35. act(() => {
  36. result.current[1]('2');
  37. });
  38. // and verify it has the changed value
  39. expect(result.current[0]).toBe('2');
  40. // then we change the value from the outside to the same
  41. // value as the one inside (2)
  42. // (this simulates the case when the inside value gets
  43. // propageted to the outside component)
  44. rerender({ outsideVal: '2' });
  45. // and verify the the value is ok
  46. expect(result.current[0]).toBe('2');
  47. // and now change the inside-value again
  48. act(() => {
  49. result.current[1]('3');
  50. });
  51. // and verify the the value is ok
  52. expect(result.current[0]).toBe('3');
  53. });
  54. });