useSyncedLocalStorageState.spec.tsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
  2. import localStorageWrapper from 'sentry/utils/localStorage';
  3. import {useSyncedLocalStorageState} from 'sentry/utils/useSyncedLocalStorageState';
  4. describe('useSyncedLocalStorageState', function () {
  5. beforeEach(() => {
  6. localStorageWrapper.clear();
  7. });
  8. const Toggle = () => {
  9. const [value, setValue] = useSyncedLocalStorageState<boolean>('key', false);
  10. return <button onClick={() => setValue(!value)}>{value ? 'On' : 'Off'}</button>;
  11. };
  12. const Text = () => {
  13. const [value] = useSyncedLocalStorageState<boolean>('key', false);
  14. return <div>{value ? 'Value is on' : 'Value is off'}</div>;
  15. };
  16. it('responds to changes in multiple components', async function () {
  17. localStorageWrapper.setItem('key', 'true');
  18. const TestComponent = () => {
  19. return (
  20. <div>
  21. <Toggle />
  22. <Text />
  23. </div>
  24. );
  25. };
  26. render(<TestComponent />);
  27. // Both components should be 'On' initially due to setItem above
  28. expect(screen.getByRole('button', {name: 'On'})).toBeInTheDocument();
  29. expect(screen.getByText('Value is on')).toBeInTheDocument();
  30. // After clicking the button, they both should be 'Off'
  31. userEvent.click(screen.getByRole('button'));
  32. expect(screen.getByRole('button', {name: 'Off'})).toBeInTheDocument();
  33. expect(screen.getByText('Value is off')).toBeInTheDocument();
  34. // localStorage should eventually have the value of false
  35. await waitFor(() => {
  36. expect(localStorageWrapper.getItem('key')).toBe('false');
  37. });
  38. });
  39. });