Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SyntaxError: Unexpected token '<' when running Jest #2605

Closed
GiaHuy216 opened this issue Jan 10, 2024 · 9 comments · Fixed by #2632
Closed

SyntaxError: Unexpected token '<' when running Jest #2605

GiaHuy216 opened this issue Jan 10, 2024 · 9 comments · Fixed by #2632

Comments

@GiaHuy216
Copy link

Describe the bug

I'm using ignite to create an expo react native app. I'm using this guide https://ignitecookbook.com/docs/recipes/GeneratorComponentTests to create component test files

Here is the first test file

import React from "react"
import { fireEvent, render, screen } from "@testing-library/react-native"
import { Profile } from "../Profile"

describe("Profile", () => {
  it("renders", () => {
    render(<Profile />)
    expect(screen.getByText("Hello")).toBeTruthy()
  })
})

I followed https://reactnativetesting.io/component/setup/ in order to install @testing-library/react-native but now I'm getting

 ● Test suite failed to run

    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 https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • 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:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /Users/giahuy/PizzaApp/app/components/specs/Profile.spec.tsx:12
            (0, react_native_1.render)(<Profile_1.Profile />);
                                       ^

    SyntaxError: Unexpected token '<'

Here my jest.config.js

const { defaults: tsjPreset } = require("ts-jest/presets")

/** @type {import('@jest/types').Config.ProjectConfig} */
module.exports = {
  ...tsjPreset,
  preset: "react-native",
  transformIgnorePatterns: [
    "<rootDir>/node_modules/(react-clone-referenced-element|@react-native-community|react-navigation|@react-navigation/.*|@unimodules/.*|native-base|react-native-code-push)",
    "jest-runner",
  ],
  testPathIgnorePatterns: ["<rootDir>/node_modules/", "<rootDir>/.maestro/", "@react-native"],
  testEnvironment: "jsdom",
  setupFiles: ["<rootDir>/test/setup.ts"],
  transform: {
    "^.+\\.spec.tsx?$": [
      "ts-jest",
      {
        tsconfig: "<rootDir>/test/test-tsconfig.json",
      },
    ],
  },
}

how can I fix it ??

Ignite version

9.3.1

Additional info

System
  platform           darwin                              
  arch               arm64                               
  cpu                8 cores      Apple M2               
  directory          PizzaApp     /Users/giahuy/PizzaApp 

JavaScript (and globally-installed packages)
  node               18.18.2      /Users/giahuy/.nvm/versions/node/v18.18.2/bin/node 
  npm                9.8.1        /Users/giahuy/.nvm/versions/node/v18.18.2/bin/npm  
    corepack         0.19.0                                                          
    npm              9.8.1                                                           
  yarn               1.22.21      /opt/homebrew/bin/yarn                             
    create-jest      29.7.0                                                          
  pnpm               -            not installed                                      
  bun                -            not installed                                      
  expo               49.0.21      managed                                            

Ignite
  ignite-cli         9.3.1        /Users/giahuy/.npm/_npx/e31027f3785124a8/node_modules/.bin/ignite      
  ignite src         build        /Users/giahuy/.npm/_npx/e31027f3785124a8/node_modules/ignite-cli/build 

Android
  java               17.0.9       /usr/bin/java                     
  android home       -            /Users/giahuy/Library/Android/sdk 

iOS
  xcode              15.1       
  cocoapods          1.14.3       /opt/homebrew/bin/pod 

Tools
  git                git version 2.39.3 (Apple Git-145)   /usr/bin/git 
@GiaHuy216 GiaHuy216 added the bug label Jan 10, 2024
@frankcalise
Copy link
Contributor

Hi @GiaHuy216

I couldn't reproduce that error exactly, but had run into the test just never completing until I removed testEnvironment: "jsdom" from the jest config. Then the test provided worked as is.

Could you paste your Profile component here as well?

@markrickert
Copy link
Member

This also might happen if you file is named .js or .ts instead of .jsx/.tsx. The "X" in the file name indicated that the compiler should expect XML in the javascript

@GiaHuy216
Copy link
Author

@frankcalise
Here is Profile component

import * as React from "react"
import { StyleProp, TextStyle, View, ViewStyle } from "react-native"
import { observer } from "mobx-react-lite"
import { colors, typography } from "app/theme"
import { Text } from "app/components/Text"

export interface ProfileProps {
  /**
   * An optional style override useful for padding & margin.
   */
  style?: StyleProp<ViewStyle>
}

/**
 * Describe your component here
 */
export const Profile = observer(function Profile(props: ProfileProps) {
  const { style } = props
  const $styles = [$container, style]

  return (
    <View style={$styles}>
      <Text style={$text}>Hello</Text>
    </View>
  )
})

const $container: ViewStyle = {
  justifyContent: "center",
}

const $text: TextStyle = {
  fontFamily: typography.primary.normal,
  fontSize: 14,
  color: colors.palette.primary500,
}

I also removed testEnvironment: "jsdom" like you said but it doesn't work .Did i miss something?

@GiaHuy216
Copy link
Author

@markrickert My component file and test file are both tsx files.

@3210jr
Copy link

3210jr commented Feb 10, 2024

@GiaHuy216 - I just got my tests to work again, had to remove: testEnvironment: "jsdom", as suggested by @frankcalise and then replaced the transform, here is what I have now as my jest.config.js (including commented out code):

const { defaults: tsjPreset } = require("ts-jest/presets")

/** @type {import('@jest/types').Config.ProjectConfig} */
module.exports = {
  ...tsjPreset,
  preset: "jest-expo",
  transformIgnorePatterns: [
    "<rootDir>/node_modules/(react-clone-referenced-element|@react-native-community|react-navigation|@react-navigation/.*|@unimodules/.*|native-base|react-native-code-push)",
    "jest-runner",
  ],
  testPathIgnorePatterns: ["<rootDir>/node_modules/", "<rootDir>/.maestro/", "@react-native", "<rootDir>/test/i18n.test.ts"],
  // testEnvironment: "jsdom",
  setupFiles: ["<rootDir>/test/setup.ts"],
  "setupFilesAfterEnv": [
    "@testing-library/jest-native/extend-expect"
  ],
  coverageDirectory: "<rootDir>/test/coverage",
  collectCoverageFrom: [
    "**/*.{js,jsx,ts,tsx}",
    "!**/node_modules/**",
    "!**/vendor/**",
    "!**/test/**",
    "!**/coverage/**",
    "!**/.expo/**",
    "!**/android/**",
    "!**/ios/**",
  ],
  // moduleNameMapper: {
  //   "app/(.*)": "<rootDir>/app/$1",
  // },
  transform:{
    // '^.+\\.test.tsx?$': ['ts-jest', {
      // tsconfig: '<rootDir>/test/test-tsconfig.json'
    // }],
    "^.+\\.[jt]sx?$": "babel-jest",
  },
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
  "globals": {
    "ts-jest": {
      "diagnostics": false
    }
  }
}

Let me know if this works, or causes other issues I haven't come across yet

@frankcalise
Copy link
Contributor

@3210jr thanks for confirming it's working. it also aligns with what I found here on RNTL's issue board: callstack/react-native-testing-library#896 (comment)

Will make that update to the boilerplate

@frankcalise
Copy link
Contributor

I can't reproduce this in the latest Ignite, @GiaHuy216 are you still experiencing issues?

@GiaHuy216
Copy link
Author

GiaHuy216 commented Feb 16, 2024

@3210jr After I copied your jest.config.js file and it worked perfectly,thank you.

@infinitered-circleci
Copy link

🎉 This issue has been resolved in version 9.6.1 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants