如何使用 Jest 测试使用 crypto 或 window.msCrypto 的函数 [英] How to use Jest to test functions using crypto or window.msCrypto

查看:19
本文介绍了如何使用 Jest 测试使用 crypto 或 window.msCrypto 的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 Jest 运行单元测试时,window.crypto API 会导致问题.我还没有找到一种在不安装其他软件包的情况下将加密合并到 Jest 中的方法,这是我无法做到的.因此,如果不使用另一个 npm 包,是否有一种方法可以测试使用 crypto.getRandomValues() 的函数,而不会使 Jest 崩溃?感谢任何链接、建议或提示

When running unit tests with Jest in react the window.crypto API is causing problems. I haven't found a way to incorporate crypto in Jest without installing other packages which is something I can't do. So without using another npm package is there a way to test functions that use: crypto.getRandomValues() in them that doesn't crash Jest? Any links, advice, or tips are appreciated

推荐答案

应该这样做.使用以下代码全局设置 crypto 属性.这将允许 Jest 访问 window.crypto 并且不会导致任何问题.

This should do it. Use the following code to set up the crypto property globally. This will allow Jest to access window.crypto and won't cause any issue.

const crypto = require('crypto');

Object.defineProperty(global.self, 'crypto', {
  value: {
    getRandomValues: arr => crypto.randomBytes(arr.length)
  }
});

这篇关于如何使用 Jest 测试使用 crypto 或 window.msCrypto 的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆