reactjs React.js中不支持crypto.getRandomValues()

ttisahbt  于 4个月前  发布在  React
关注(0)|答案(2)|浏览(72)

有一个npm包,我们为我们的团队使用,在里面我们使用这个uuidjs。现在我已经安装了这个自定义的npm包在我的testing-library测试的React-App上。
当我测试从这个自定义包中导入文件的组件时,它有uuidjs,我得到以下错误:

crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported

字符串
我知道这个问题的答案是install react-native-get-random-values。但我的困惑是,我可以在使用React.js的CRA中安装这个吗?react-native与它有任何关系还是独立的?

kd3sttzy

kd3sttzy1#

问题

当你运行你的测试时,我怀疑你是在Node.js中运行的测试环境中运行它。crypto.getRandomValues只在web API中可用。它不存在于crypto下的Node中,请参阅Node的documentation on crypto。Node确实提供了一个web加密API,它有getRandomValues,但uuid库不会知道它。

解决方案

你可以自己模拟或polyfill crypto.getRandomValues,参见:How to use Jest to test functions using crypto or window.msCrypto

ds97pgxw

ds97pgxw2#

得到了同样的问题,并能够解决与polyfill。
jest.config.ts中添加了以下配置文件

...
setupFiles: ['./jest.polyfills.ts'],
setupFilesAfterEnv: ['<rootDir>/src/setup-tests.ts'],
...

字符串
已将jest.polyfills.ts文件添加到项目根目录。

if (typeof global.crypto !== 'object') {
    global.crypto = crypto;
}

if (typeof global.crypto.getRandomValues !== 'function') {
    global.crypto.getRandomValues = getRandomValues;
}

function getRandomValues(array) {
    return crypto.webcrypto.getRandomValues(array);
}

相关问题