tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

Deferred.test.ts (1632B)


      1 /**
      2 * @license
      3 * Copyright 2023 Google Inc.
      4 * SPDX-License-Identifier: Apache-2.0
      5 */
      6 
      7 import {describe, it} from 'node:test';
      8 
      9 import expect from 'expect';
     10 import sinon from 'sinon';
     11 
     12 import {Deferred} from './Deferred.js';
     13 
     14 describe('DeferredPromise', function () {
     15  it('should catch errors', async () => {
     16    // Async function before try/catch.
     17    async function task() {
     18      await new Promise(resolve => {
     19        return setTimeout(resolve, 50);
     20      });
     21    }
     22    // Async function that fails.
     23    function fails(): Deferred<void> {
     24      const deferred = Deferred.create<void>();
     25      setTimeout(() => {
     26        deferred.reject(new Error('test'));
     27      }, 25);
     28      return deferred;
     29    }
     30 
     31    const expectedToFail = fails();
     32    await task();
     33    let caught = false;
     34    try {
     35      await expectedToFail.valueOrThrow();
     36    } catch (err) {
     37      expect((err as Error).message).toEqual('test');
     38      caught = true;
     39    }
     40    expect(caught).toBeTruthy();
     41  });
     42 
     43  it('Deferred.race should cancel timeout', async function () {
     44    const clock = sinon.useFakeTimers();
     45 
     46    try {
     47      const deferred = Deferred.create<void>();
     48      const deferredTimeout = Deferred.create<void>({
     49        message: 'Race did not stop timer',
     50        timeout: 100,
     51      });
     52 
     53      clock.tick(50);
     54 
     55      await Promise.all([
     56        Deferred.race([deferred, deferredTimeout]),
     57        deferred.resolve(),
     58      ]);
     59 
     60      clock.tick(150);
     61 
     62      expect(deferredTimeout.value()).toBeInstanceOf(Error);
     63      expect(deferredTimeout.value()?.message).toContain('Timeout cleared');
     64    } finally {
     65      clock.restore();
     66    }
     67  });
     68 });