在玩笑中模拟 window.crypto.getRandomValues

Wir*_*nan 2 javascript cryptography mocking jestjs

我想开玩笑地嘲笑window.crypto.getRandomValues一下。我已经尝试过了jest.spyOn,但没有成功。

sli*_*wp2 8

您可以使用Object.defineProperty来定义window.crypto属性及其值。

\n

例如

\n

index.ts:

\n
export function main() {\n  let byteArray = new Uint8Array(1);\n  return window.crypto.getRandomValues(byteArray);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

index.test.ts:

\n
import { main } from \'./\';\n\ndescribe(\'63484075\', () => {\n  it(\'should pass\', () => {\n    const mGetRandomValues = jest.fn().mockReturnValueOnce(new Uint32Array(10));\n    Object.defineProperty(window, \'crypto\', {\n      value: { getRandomValues: mGetRandomValues },\n    });\n    expect(main()).toEqual(new Uint32Array(10));\n    expect(mGetRandomValues).toBeCalledWith(new Uint8Array(1));\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

带有覆盖率报告的单元测试结果:

\n
 PASS  src/stackoverflow/63484075/index.test.ts\n  63484075\n    \xe2\x9c\x93 should pass (6ms)\n\n----------|----------|----------|----------|----------|-------------------|\nFile      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |\n----------|----------|----------|----------|----------|-------------------|\nAll files |      100 |      100 |      100 |      100 |                   |\n index.ts |      100 |      100 |      100 |      100 |                   |\n----------|----------|----------|----------|----------|-------------------|\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        5.759s, estimated 13s\n
Run Code Online (Sandbox Code Playgroud)\n

源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/63484075

\n