如何解决嘲笑window.crypto.getRandomValues开玩笑
我想开玩笑地嘲笑window.crypto.getRandomValues
。我尝试过jest.spyOn
,但没有成功。
解决方法
您可以使用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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。