You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中Jest测试报错:SyntaxError: Unexpected token 'export'

解决React Native Jest测试中@fortawesome/react-native-fontawesome的语法错误

问题描述

在React Native项目中对登录页面执行元素渲染测试,运行yarn test时出现语法错误,报错指向@fortawesome/react-native-fontawesome模块的export语句,需要修复该问题使测试通过。

报错详情

Details:

    C:\Users\Hp\OneDrive\Desktop\testing with jest\testingJest\node_modules\@fortawesome\react-native-fontawesome\index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as FontAwesomeIcon } from './dist/components/FontAwesomeIcon'
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

       8 |   StyleSheet,
       9 | } from 'react-native';
    > 10 | import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome';
         | ^
      11 | import {faPhone} from '@fortawesome/free-solid-svg-icons';
      12 | import {faEye} from '@fortawesome/free-solid-svg-icons';
      13 | import Svg, {Path} from 'react-native-svg';

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)
      at Object.require (screens/LoginScreen.js:10:1)
      at Object.require (__tests__/Login.test.tsx:3:1)

测试代码(Login.test.tsx)

import React from 'react';
import {render} from '@testing-library/react-native';
import LoginScreen from '../screens/LoginScreen';

describe('LoginScreen', () => {
  test('renders correctly', () => {
    const {getByTestId, getByPlaceholderText, getByText} = render(
      <LoginScreen />,
    );
    const container = getByTestId('login-container');
    expect(container).toBeTruthy();

    const textConnection = getByText('Connexion');
    expect(textConnection).toBeTruthy();

    const placeTextPhone = getByPlaceholderText('Phone Number');
    expect(placeTextPhone).toBeTruthy();

    const placePassword = getByPlaceholderText('Password');
    expect(placePassword).toBeTruthy();
  });
});

配置文件

jest.config.js

module.exports = {
   preset: 'react-native',
};

babel.config.js

module.exports = {
   presets: ['module:@react-native/babel-preset'],
};

解决方案

这个错误是因为Jest默认不转译node_modules目录下的ES模块代码,而@fortawesome/react-native-fontawesome使用了ES模块的export语法,导致Jest无法解析。只需修改Jest配置让它转译指定的模块即可:

  1. 更新jest.config.js,添加transformIgnorePatterns配置项:
module.exports = {
  preset: 'react-native',
  transformIgnorePatterns: [
    'node_modules/(?!(@fortawesome|react-native-svg)/)'
  ],
};

这里的配置表示:排除node_modules下除了@fortawesome和react-native-svg之外的模块,让Jest转译这两个模块的代码(你的项目里也用到了react-native-svg,所以一并加入)。

  1. 保持babel.config.js的现有配置不变,module:@react-native/babel-preset已经包含了React Native项目所需的转译规则。

修改完成后,重新运行yarn test,语法错误即可消除,测试应该能正常执行。

内容的提问来源于stack exchange,提问作者MehKadiri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 11:17:23