reactjs - 使用 Jest + React Native 测试组件中导入的图像

标签 reactjs react-native jestjs

这是我的 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') 。

这是我的文件夹结构:

enter image description here

测试在 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 to Image. in Image (at ....

最佳答案

您可以尝试manually mock使用

测试文件中的图像
jest.mock('../../../assets/images/load_error.png')

关于reactjs - 使用 Jest + React Native 测试组件中导入的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57905383/

相关文章:

javascript - 从使用 React 和 Webpack 构建的网站的 url 中删除 .html 扩展名

javascript - 通过 redux 更改状态后如何更新 React 组件?

javascript - react 三渲染器多面体几何错误

android - 来自 React Native 的 AsyncStorage 中的 Promises

java - 如何设置可以在样式中使用的变量

node.js - Jest 模拟 Stripe

javascript - 按多个字段过滤 Firebase

javascript - 在 React Native 中链接 CSS 框架

reactjs - 使用 babel-jest 来开 Jest 但仍然出现语法错误

react-native - 如何解决测试中的 NativeModule.RNLocalize is null 错误?