【发布时间】:2019-09-12 11:07:54
【问题描述】:
这是我的 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 正在尝试渲染: 重新
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。 在图像中(在 ....
【问题讨论】:
-
您的
png导入正在被fileMock.js模拟 - 它基本上会跳过加载任何真实文件而只返回一个存根字符串。您可以尝试使用jest.mock(pathToImage)模拟该文件并返回您自己的模拟值(一个字符串),然后您可以断言源是否已使用您提供的模拟字符串更新。 -
@YuruiZhang 我应该把模拟放在哪里?在笑话文件中?让我更新我的测试代码。
-
实际上可以发布您的文件夹结构吗?如果
assets不在src之外,我认为开玩笑可能会遇到一些问题。 -
@YuruiZhang 我已经更新了文件夹的照片。
-
对,在您的问题中您提到了
When it don't found the file.png it should look for the error image, which is a require('error.png')- 很高兴看到它是如何处理的......可能是您的测试在某些异步操作的回调实际触发之前结束。您的代码似乎涉及更新状态,在您的测试中,您应该将更改状态的操作包装在act中,请参阅 reactjs.org/docs/test-renderer.html#testrendereract
标签: reactjs react-native jestjs