本文介绍了如何使用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

推荐答案

这应该这样做。使用以下代码全局设置加密属性。这将允许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测试函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 21:39