delay.test.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { describe, expect, it } from '@jest/globals'
  2. import { AbortController } from './AbortController.js'
  3. import delay from './delay.js'
  4. describe('delay', () => {
  5. it('should wait for the specified time', async () => {
  6. const start = Date.now()
  7. await delay(100)
  8. // 100 is less of a rule, more of a guideline
  9. // according to CI
  10. expect(Date.now() - start).toBeGreaterThanOrEqual(90)
  11. })
  12. it('should reject if signal is already aborted', async () => {
  13. const signal = { aborted: true }
  14. const start = Date.now()
  15. await expect(delay(100, { signal })).rejects.toHaveProperty('name', 'AbortError')
  16. // should really be instant but using a very large range in case CI decides
  17. // to be super busy and block the event loop for a while.
  18. expect(Date.now() - start).toBeLessThan(50)
  19. })
  20. it('should reject when signal is aborted', async () => {
  21. const controller = new AbortController()
  22. const start = Date.now()
  23. const testDelay = delay(1000, { signal: controller.signal })
  24. await Promise.all([
  25. delay(50).then(() => controller.abort()),
  26. expect(testDelay).rejects.toHaveProperty('name', 'AbortError'),
  27. ])
  28. // should have rejected before the timer is done
  29. const time = Date.now() - start
  30. expect(time).toBeGreaterThanOrEqual(30)
  31. expect(time).toBeLessThan(900)
  32. })
  33. })