【发布时间】:2020-10-02 03:43:38
【问题描述】:
我尝试使用包 uuid 并响应本机获取随机值来创建随机 uuid。一切都很好并且工作正常。但是当我尝试使用 jest 运行我的测试文件时,我收到一个错误无法读取未定义的属性“getRandomBase64”。 如何解决这个错误?
谢谢。
【问题讨论】:
标签: react-native jestjs
我尝试使用包 uuid 并响应本机获取随机值来创建随机 uuid。一切都很好并且工作正常。但是当我尝试使用 jest 运行我的测试文件时,我收到一个错误无法读取未定义的属性“getRandomBase64”。 如何解决这个错误?
谢谢。
【问题讨论】:
标签: react-native jestjs
react-native-get-random-values 是一个原生模块,所以在运行单元测试时需要模拟它。
一种方法如下:转到您的 __mocks__ 文件夹(如果不存在,则在项目的根目录中创建它)并放置一个名为 react-native-get-random-values.js 的文件(名称很重要)以下内容:
export default {
getRandomBase64: jest.fn().mockImplementation(() => {
console.log("getRandomBase64 mock called");
return "mockedBase64";
})
};
要了解有关模拟整个模块的更多信息,请阅读Jest docs
【讨论】:
我遇到了同样的问题,但上面的回答都不适合我。
在我的测试文件顶部添加这个模拟解决了这个问题:
jest.mock('react-native-get-random-values', () => ({
getRandomBase64: jest.fn(),
}));
aav7fl 在this GitHub issue 上找到的解决方案。
我知道这个问题已经 5 个月了,但它可能对其他人有所帮助。
【讨论】:
尝试在根应用中导入“react-native-get-random-values”
import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
import '@react-native-firebase/crashlytics';
import 'react-native-get-random-values';
console.disableYellowBox = true
AppRegistry.registerComponent(appName, () => App);
这是链接问题https://github.com/react-native-webview/react-native-webview/issues/1312
【讨论】:
最后我可以通过在我的 package.json 文件中添加 react native get random values 和 uuid 来修复这个错误,就像这样。
"transformIgnorePatterns": [
"/node_modules/(?!native-base|@react-native-community/netinfo|@react-native-community/async-storage|@react-native-community/geolocation|react-native-permissions|uuid|react-native-get-random-values)/"
]
【讨论】: