这是我的 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');
它试图渲染这个:
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
在处理错误之后,将返回所需的错误图像。它在浏览器上完美运行,没有警告或错误。但我在使用 jest 进行测试时遇到了一些麻烦。
但由于某种原因它找不到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 文件夹中的图像组件。
Jest 中的错误消息:
Cannot log after tests are done. Did you forget to wait for something async in your test? Attempted to log "Warning: Failed prop type: Invalid prop
source
supplied toImage
. in Image (at ....
最佳答案
您可以尝试manually mock使用
测试文件中的图像jest.mock('../../../assets/images/load_error.png')
关于reactjs - 使用 Jest + React Native 测试组件中导入的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57905383/