timer.spec.tsx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import {Timer} from './timer';
  2. // biome-ignore lint/correctness/useHookAtTopLevel: not a hook
  3. jest.useFakeTimers();
  4. describe('Replay Timer', () => {
  5. it('works', () => {
  6. const timer = new Timer();
  7. timer.start();
  8. jest.advanceTimersByTime(1008);
  9. timer.stop();
  10. expect(timer.getTime()).toBe(1008);
  11. jest.advanceTimersByTime(1008);
  12. expect(timer.getTime()).toBe(1008);
  13. timer.resume();
  14. jest.advanceTimersByTime(1008);
  15. timer.stop();
  16. expect(timer.getTime()).toBe(2016);
  17. });
  18. it('sets a custom time', () => {
  19. const timer = new Timer();
  20. timer.setTime(5678);
  21. expect(timer.getTime()).toBe(5678);
  22. jest.advanceTimersByTime(1008);
  23. // not started yet
  24. expect(timer.getTime()).toBe(5678);
  25. // starting the timer will wipe out the set time!
  26. timer.start();
  27. expect(timer.getTime()).toBe(0);
  28. jest.advanceTimersByTime(1008);
  29. expect(timer.getTime()).toBe(1008);
  30. // so that the timer doesn't infinitely run
  31. timer.stop();
  32. });
  33. it('handles multiple callbacks', () => {
  34. const timer = new Timer();
  35. const spy1 = jest.fn();
  36. const spy2 = jest.fn();
  37. const spy3 = jest.fn();
  38. const spy4 = jest.fn();
  39. timer.addNotificationAtTime(4000, spy3);
  40. timer.addNotificationAtTime(1000, spy1);
  41. timer.addNotificationAtTime(1000, spy2);
  42. timer.addNotificationAtTime(2000, spy4);
  43. timer.start();
  44. // Syncs with RAF, so each tick of the timer should be +16ms
  45. jest.advanceTimersByTime(1008);
  46. timer.stop();
  47. expect(spy1).toHaveBeenCalledTimes(1);
  48. expect(spy2).toHaveBeenCalledTimes(1);
  49. expect(spy3).toHaveBeenCalledTimes(0);
  50. expect(spy4).toHaveBeenCalledTimes(0);
  51. });
  52. });