summaryrefslogtreecommitdiffhomepage
path: root/packages/server/src/helpers/iso/isoCrypto/getWebCrypto.test.ts
blob: 9ab0ad270ae9a66bc6da453db90dee38a8c45ec3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { assertEquals, assertRejects } from 'https://deno.land/std@0.198.0/assert/mod.ts';
import { returnsNext, stub } from 'https://deno.land/std@0.198.0/testing/mock.ts';

import { _getWebCryptoInternals, getWebCrypto, MissingWebCrypto } from './getWebCrypto.ts';

Deno.test('should return globalThis.crypto when present', async () => {
  // Clear whatever version of crypto might have been set
  _getWebCryptoInternals.setCachedCrypto(undefined);

  // Pretend globalThis.crypto exists
  const newGlobalThisCrypto = {};
  const mockGlobalThisCrypto = stub(
    _getWebCryptoInternals,
    'stubThisGlobalThisCrypto',
    // @ts-ignore: globalThis.crypto
    returnsNext([newGlobalThisCrypto]),
  );

  const returnedCrypto = await getWebCrypto();

  assertEquals(returnedCrypto, newGlobalThisCrypto);

  mockGlobalThisCrypto.restore();
});

Deno.test('should raise MissingWebCrypto error when nothing is available', async () => {
  // Clear whatever version of crypto might have been set
  _getWebCryptoInternals.setCachedCrypto(undefined);

  // Pretend globalThis.crypto doesn't exist
  const mockGlobalThisCrypto = stub(
    _getWebCryptoInternals,
    'stubThisGlobalThisCrypto',
    // @ts-ignore: globalThis.crypto
    returnsNext([undefined]),
  );

  await assertRejects(
    () => getWebCrypto(),
    MissingWebCrypto,
    'Crypto API could not be located',
  );

  mockGlobalThisCrypto.restore();
});