【问题标题】:how can I test react native components that includes PNGs images with Jest如何使用 Jest 测试包含 PNG 图像的本机组件
【发布时间】:2021-12-28 12:00:23
【问题描述】:

我测试了我的应用程序,该应用程序的导航在节点模块中有 png 图像,但测试失败。

App.js的源代码

import React from 'react';
import {SafeAreaView} from 'react-native';
import {styles} from './src/assets/styles';
import {AppStack} from './src/components/navs/stacks/AppStack';

const App = () => {
  //TODO: Designing ui for spend and scheduled :progress
  // doing list of data from utils/index.js :done
  //fech those data to screen that needs them
  return (
    <SafeAreaView style={styles.app}>
      <AppStack />
    </SafeAreaView>
  );
};

export default App;

App-test.js

import 'react-native';
import React from 'react';
import App from '../App';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

it('renders correctly', () => {
  renderer.create(<App />);
});

预期结果: 测试应该呈现我的应用入口点,即 App.js 实际结果

Janviers-MacBook-Pro:credex janvier$ npm test

> credex@0.0.1 test
> jest

 FAIL  __tests__/App-test.js
  ● Test suite failed to run

    /Volumes/D/Coding/credex/node_modules/@react-navigation/elements/lib/commonjs/assets/back-icon.png:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){�PNG
                                                                                             

    SyntaxError: Invalid or unexpected token

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
      at Object.<anonymous> (node_modules/@react-navigation/elements/lib/commonjs/index.tsx:20:3) 

【问题讨论】:

    标签: javascript react-native jestjs


    【解决方案1】:

    错误原因是 Jest 未能将 .png 文件(或任何图像文件)的二进制代码解释为 .js。

    解决方案或更确切地说是解决方法是在 Jest 遇到图像文件时模拟默认响应。

    步骤:

    1. 在名为 __mock__(或任何名称)的文件夹中创建一个名为 ImageMock.js(如果您使用的是 TypeScript,则为 .tsx)的文件。

    YourApp/__mock__/ImageMock.js

    1. 在 ImageMock.js 中写 export default '';
    2. 在 package.json 的 jest 键中添加具有以下值的 moduleNameMapper 键
    "jest": {
      "moduleNameMapper": {
      "\\.(png|jpg|ico|jpeg|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mock__/ImageMock.js"
      }
    }
    

    注意:对于您的特定错误,只需要 moduleNameMapper 键值中的 png。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 2018-03-24
      • 2020-05-05
      • 2020-12-02
      相关资源
      最近更新 更多