forked from PlasmoHQ/storage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jest.setup.mts
67 lines (59 loc) · 1.59 KB
/
jest.setup.mts
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { jest } from "@jest/globals"
/**
* Mimic the webcrypto API without implementing the actual encryption
* algorithms. Only the mock implementations used by the SecureStorage
*/
export const cryptoMock = {
subtle: {
importKey: jest.fn(),
deriveKey: jest.fn(),
decrypt: jest.fn(),
encrypt: jest.fn(),
digest: jest.fn()
},
getRandomValues: jest.fn()
}
cryptoMock.subtle.importKey.mockImplementation(
(format, keyData, algorithm, extractable, keyUsages) => {
return Promise.resolve({
format,
keyData,
algorithm,
extractable,
keyUsages
})
}
)
cryptoMock.subtle.deriveKey.mockImplementation(
(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages) => {
return Promise.resolve({
algorithm,
baseKey,
derivedKeyAlgorithm,
extractable,
keyUsages
})
}
)
cryptoMock.subtle.decrypt.mockImplementation((_, __, data: ArrayBufferLike) => {
return Promise.resolve(new Uint8Array(data))
})
cryptoMock.subtle.encrypt.mockImplementation((_, __, data: ArrayBufferLike) => {
return Promise.resolve(new Uint8Array(data))
})
cryptoMock.subtle.digest.mockImplementation((_, __) => {
return Promise.resolve(new Uint8Array([0x01, 0x02, 0x03, 0x04]))
})
cryptoMock.getRandomValues.mockImplementation((array: Array<any>) => {
for (let i = 0; i < array.length; i++) {
array[i] = Math.floor(Math.random() * 256)
}
return array
})
// The globalThis does not define crypto by default
Object.defineProperty(globalThis, "crypto", {
value: cryptoMock,
writable: true,
enumerable: true,
configurable: true
})