delay.test.js 1.3 KB

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