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

时间:2019-09-12 11:07:54

标签: reactjs react-native jestjs

这是我的package.json配置:

private string Solve(string sentence)
{
    if (sentence != null && sentence.Length > 0)
    {
        return sentence[0].ToString().ToUpper() + sentence.Substring(1).ToLower();
    }
    else
    {
        return sentence;
    }
}

我在组件内部需要此图像:

"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}]} /> ); 将返回所需的errorImage。它在浏览器上完美运行,没有警告或错误。但是我在开玩笑测试时遇到了一些麻烦。

但是由于某种原因,它找不到load_error.png图像。这是我的文件夹结构:

state.source

无论我做什么,错误图像都会为空。 ?

这是我的测试:

        ___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(); }); 时,它应该寻找错误图像,该图像是图像组件内部的require('error.png')。

这是我的文件夹结构:

enter image description here

  

该测试正在Attachments.test.js中运行,测试附件.js   文件,它使用底部ui文件夹中的图像componente   图片。

玩笑的错误消息:

  

测试完成后无法记录。你忘了等什么吗   在测试中异步?       尝试记录“警告:道具类型失败:提供给file.png的道具source无效。           在图片中(位于....

3 个答案:

答案 0 :(得分:3)

您可以尝试使用

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

答案 1 :(得分:0)

在笑话配置对象中提供rootDir可能会解决此问题。

类似的东西:

{
  "jest": {
    "rootDir": "../",
    "preset": "react-native",
    // other config goes here...
  }
}

引用:https://jestjs.io/docs/en/configuration#rootdir-string

答案 2 :(得分:0)

如果您在 React 或 React Native 中测试图像的默认或非默认导出有问题,您可以使用此功能:

jest.mock("../src/Icon", () => {
  return {
    default: "whatever.png",
  };
});