首页 > 解决方案 > 使用 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 的道具无效(在 ....

标签: reactjsreact-nativejestjs

解决方案


您可以尝试使用手动模拟测试文件中的图像

jest.mock('../../../assets/images/load_error.png')

推荐阅读