Wir*_*nan 2 javascript cryptography mocking jestjs
我想开玩笑地嘲笑window.crypto.getRandomValues一下。我已经尝试过了jest.spyOn,但没有成功。
您可以使用Object.defineProperty来定义window.crypto属性及其值。
例如
\nindex.ts:
export function main() {\n let byteArray = new Uint8Array(1);\n return window.crypto.getRandomValues(byteArray);\n}\nRun Code Online (Sandbox Code Playgroud)\nindex.test.ts:
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});\nRun 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\nRun Code Online (Sandbox Code Playgroud)\n源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/63484075
\n