reactjs - 使用 Jest + React Native 测试组件中导入的图片
问题描述
这是我的 package.json 配置:
"jest": {
"preset": "react-native",
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
},
"moduleNameMapper": {
"\\.(pdf|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js"
}
},
我在组件内部需要这张图片:
const errorImage = require('../../../assets/images/load_error.png');
Wich 正在尝试渲染:re
return (
<Image
source={ this.state.source }
onError={ this._handleError }
resizeMode={resizeMode}
style={[this.props.style, {height: this.state.height, width: this.state.width}]}
/>
);
处理错误后,将state.source
返回所需的 errorImage。它在浏览器上完美运行,没有警告或错误。但是我在玩笑话时遇到了一些麻烦。
但由于某种原因,它找不到 load_error.png 图像。这是我的文件夹结构:
___mocks___
--> fileMocks.js
--> load_error.png
__test__
--> componentes
--> --> imageComponent.test.js
components
--> imageComponent.js
无论我做什么,错误图像都会变空。
这是我的测试:
const props = {
author: 'Random Author',
isSent: true,
data:{origin:1},
attachments:{
4 : {
type: 2, //file, pdf, word, etc...
preview: 'pdf',
url: 'file.png',
},
},
}
test('renders correctly', () => {
const ActIndc = renderer.create(<Attachments {...props} />).toJSON();
expect(ActIndc).toMatchSnapshot();
});
当它没有找到时,file.png
它应该寻找错误图像,这是图像组件中的一个 require('error.png') 。
这是我的文件夹结构:
测试在 Attachements.test.js 中运行,测试 attachment.js 文件,该文件使用图像底部 ui 文件夹中的图像组件。
来自开玩笑的错误消息:
测试完成后无法登录。您是否忘记在测试中等待异步内容?尝试记录“警告:道具类型失败:
source
提供给Image
. in Image 的道具无效(在 ....
解决方案
您可以尝试使用手动模拟测试文件中的图像
jest.mock('../../../assets/images/load_error.png')
推荐阅读
- android - 安卓应用证书
- python - “TypeError:如果启用引用,则必须设置quotechar”在csv模块中
- flutter - Flutter 转换货币格式
- c# - 参考字符串参数为空?
- string - 如何将字符串列转换为具有浮点值pyspark的udt向量
- css - 移动视图上的重叠文本
- javascript - React 在按钮单击时渲染新图像(每次检索图像的新 fetch 调用)
- amazon-web-services - 使用 AWS 负载均衡器之一对 gRPC 请求进行负载均衡
- swift - 如何禁用允许删除提示?
- reactjs - 静态和动态Key和Value的setState的区别?