我想开玩笑地嘲笑window.crypto.getRandomValues
。我尝试过jest.spyOn
,但没有成功。
答案 0 :(得分:1)
您可以使用Object.defineProperty来定义window.crypto
属性及其值。
例如
index.ts
:
export function main() {
let byteArray = new Uint8Array(1);
return window.crypto.getRandomValues(byteArray);
}
index.test.ts
:
import { main } from './';
describe('63484075', () => {
it('should pass', () => {
const mGetRandomValues = jest.fn().mockReturnValueOnce(new Uint32Array(10));
Object.defineProperty(window, 'crypto', {
value: { getRandomValues: mGetRandomValues },
});
expect(main()).toEqual(new Uint32Array(10));
expect(mGetRandomValues).toBeCalledWith(new Uint8Array(1));
});
});
具有覆盖率报告的单元测试结果:
PASS src/stackoverflow/63484075/index.test.ts
63484075
✓ should pass (6ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.759s, estimated 13s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/63484075