最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - SyntaxError: C:zeronode_modulesreact-nativeLibrariesComponentsTouchableTouchableOpacity.js: Missing initializer in

programmeradmin1浏览0评论

I'm trying to write tests for my React Native app (using TypeScript). All my unit tests pass without issues, but when writing component tests, I encounter the following error:

  ● ButtonComponent › calls onPress when pressed                                                                                                           
                                                                                                                                                           
    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see  for how to enable it.
     • If you are trying to use TypeScript, see 
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    
    For information about custom transformations, see:
    

    Details:

    SyntaxError: C:\zero\node_modules\react-native\Libraries\Components\Touchable\TouchableOpacity.js: Missing initializer in const declaration. (330:26)  

      328 | }
      329 |
    > 330 | const Touchable: component(
          |                           ^
      331 |   ref: React.RefSetter<React.ElementRef<typeof Animated.View>>,
      332 |   ...props: Props
      333 | ) = React.forwardRef((props, ref) => (

       9 |
      10 |     const {getByText} = render(
    > 11 |       <TouchableOpacity onPress={mockOnPress}>
         |        ^
      12 |         <Text>Click Me</Text>
      13 |       </TouchableOpacity>,
      14 |     );

Code: Test File:

// ButtonComponent.test.js
import React from 'react';
import {render, fireEvent} from '@testing-library/react-native';
import {TouchableOpacity, Text} from 'react-native'; // Import required components

describe('ButtonComponent', () => {
  it('calls onPress when pressed', () => {
    const mockOnPress = jest.fn();

    const {getByText} = render(
      <TouchableOpacity onPress={mockOnPress}>
        <Text>Click Me</Text>
      </TouchableOpacity>,
    );

    fireEvent.press(getByText('Click Me')); // Simulate pressing the button
    expect(mockOnPress).toHaveBeenCalled(); // Check if onPress was called
  });
});

Babel config:

module.exports = {
  presets: [
    'module:metro-react-native-babel-preset',
    '@babel/preset-react',
    '@babel/preset-typescript',
    '@babel/preset-env',
  ],
  plugins: [
    [
      'module-resolver',
      {
        alias: {
          '@': './src',
        },
      },
    ],
    [
      'module:react-native-dotenv',
      {
        moduleName: '@env',
        path: '.env',
      },
    ],
  ],
};

Jest config:

module.exports = {
  preset: 'react-native',
  transform: {
    '^.+\\.(js|jsx|ts|tsx)$': 'babel-jest',
  },
  moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'json', 'node'], // Supports different file types
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1', // Optional alias to map imports
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/__mocks__/fileMock.js',
    '^@env$': '<rootDir>/src/types/env.d.ts',
  },
  transformIgnorePatterns: [
    'node_modules/(?!(react-native|@react-native|@react-native(-community)|react-native-gesture-handler|react-native-reanimated|@react-navigation)/)',
  ],
  testPathIgnorePatterns: ['/node_modules/', '/dist/'],
  testEnvironment: 'node',
  collectCoverage: true,
  coverageReporters: ['json', 'lcov', 'text', 'clover'],
  verbose: true,
};

Ts config:

{
  "extends": "@react-native/typescript-config/tsconfig.json",
  "compilerOptions": {
    "jsx": "react-native",
    "allowJs": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    },
    "allowSyntheticDefaultImports": true,
    "strict": true,  
    "esModuleInterop": true,  
    "resolveJsonModule": true  
  },
  "typeRoots": ["./src/types", "./node_modules/@types"],
  "include": ["src/**/*", "./App.tsx", "__tests__"]
}

Package json:

{
  "name": "zero",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "lint": "eslint .",
    "start": "react-native start",
    "test": "jest .",
    "test:watch": "jest --watch",
    "test:coverage": "jest --collectCoverage --coverageDirectory=\"./coverage\"",
    "commit": "cz",
    "prepare": "husky",
    "pretty": "prettier --write ."
  },
  "dependencies": {
    "@babel/core": "^7.26.7",
    "@babel/runtime": "^7.26.7",
    "@react-navigation/bottom-tabs": "^7.2.0",
    "@react-navigation/native": "^7.0.14",
    "@react-navigation/native-stack": "^7.2.0",
    "@reduxjs/toolkit": "^2.5.1",
    "axios": "^1.7.9",
    "axios-mock-adapter": "^2.1.0",
    "react": "18.3.1",
    "react-native": "^0.77.0",
    "react-native-error-boundary": "^1.2.7",
    "react-native-fast-image": "^8.6.3",
    "react-native-gesture-handler": "^2.22.1",
    "react-native-keychain": "^9.2.2",
    "react-native-reanimated": "^3.16.7",
    "react-native-safe-area-context": "^5.1.0",
    "react-native-screens": "^4.6.0",
    "react-native-splash-screen": "^3.3.0",
    "react-native-toast-message": "^2.2.1",
    "react-native-vector-icons": "^10.2.0",
    "react-redux": "^9.2.0"
  },
  "devDependencies": {
    "@babel/plugin-transform-react-jsx": "^7.25.9",
    "@babel/preset-env": "^7.26.7",
    "@babel/preset-react": "^7.26.3",
    "@babel/preset-typescript": "^7.26.0",
    "@react-native-community/cli": "15.0.1",
    "@react-native-community/cli-platform-android": "15.0.1",
    "@react-native-community/cli-platform-ios": "15.0.1",
    "@react-native/babel-preset": "^0.77.0",
    "@react-native/eslint-config": "^0.77.0",
    "@react-native/metro-config": "^0.77.0",
    "@react-native/typescript-config": "^0.77.0",
    "@testing-library/react-native": "^12.9.0",
    "@types/jest": "^29.5.14",
    "@types/react": "^18.3.18",
    "@types/react-native": "^0.72.8",
    "@types/react-native-dotenv": "^0.2.2",
    "@types/react-native-vector-icons": "^6.4.18",
    "@types/react-test-renderer": "^18.0.0",
    "babel-jest": "^29.7.0",
    "babel-plugin-module-resolver": "^5.0.2",
    "commitizen": "^4.3.1",
    "cz-conventional-changelog": "^3.3.0",
    "eslint": "^8.19.0",
    "eslint-plugin-testing-library": "^7.1.1",
    "husky": "^9.1.7",
    "jest": "^29.7.0",
    "jest-react-native": "^18.0.0",
    "metro-react-native-babel-preset": "^0.77.0",
    "prettier": "2.8.8",
    "react-native-dotenv": "^3.4.11",
    "react-test-renderer": "^18.2.0",
    "ts-jest": "^29.2.5",
    "typescript": "5.0.4"
  },
  "engines": {
    "node": ">=18"
  },
  "config": {
    "commitizen": {
      "path": "./node_modules/cz-conventional-changelog"
    }
  }
}

I have been stuck on this issue for 2 days and haven't found a solution. Could someone please help me with fixing the Jest configuration or guide me on how to enable Jest to handle this component correctly?

What I Tried: I configured Jest to work with React Native and TypeScript, ensuring that the necessary Babel presets were in place to handle the code transformation. I also set up custom transformIgnorePatterns to ensure that certain node_modules were included in the transformation process. I wrote a simple component test where a TouchableOpacity is pressed, and I used jest.fn() to check if the onPress callback was triggered.

What I Expected: I expected the test to run successfully, simulating a press on the button and confirming that the onPress function was called. The component test should have passed without issues.

What Actually Happened: Instead of the test passing, I encountered a SyntaxError indicating that Jest was unable to parse the TouchableOpacity component due to an issue with its syntax (missing initializer in a const declaration). The error message suggests that Jest could not transform the file correctly, which prevented the test from running

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论