如何使用 Jest 来测试使用 crypto 或 window.msCrypto 的函数

新手上路,请多包涵

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

原文由 CoderLee 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 738
2 个回答

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

 const crypto = require('crypto');

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

原文由 Hardik Modha 发布,翻译遵循 CC BY-SA 4.0 许可协议

与@RwwL 一样,接受的答案对我不起作用。我发现这个库中使用的 polyfill 确实有效: commit with polyfill

 //setupTests.tsx
const nodeCrypto = require('crypto');
window.crypto = {
  getRandomValues: function (buffer) {
    return nodeCrypto.randomFillSync(buffer);
  }
};

 //jest.config.js
module.exports = {
 //...
  setupFilesAfterEnv: ["<rootDir>/src/setupTests.tsx"],
};

原文由 mitchelc 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题