Encountering "Unexpected token *" error when using Jest on an import statement

What could be the reason for Jest failing with the error message "Unexpected token *" when encountering a simple import statement?

Error log:

Admin@Admin-PC MINGW32 /d/project (master)
$ npm run test

> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8e5d1e9d8d8e89886988699">[email protected]</a> test D:\project
> jest

FAIL __tests__/App-test.tsx
...
Test Suites: 3 failed, 3 total
Tests:       2 failed, 2 total
Snapshots:   0 total
Time:        22.774s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c489bd85b4b484f4eaf4eaf5">[email protected]</a> test: `jest`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="682511291818285846584659">[email protected]</a> test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Admin\AppData\Roaming\Roaming\npm-cache\_logs\2019-04-22T11_52_36_984Z-debug.log

package.json file:

...

babel.config.js file:

...

jest.config.js file:

...

Note: I am utilizing the react-native type-script template by running

react-native init MyApp --template typescript

Answer №1

It has come to my attention that certain react-native libraries are being distributed with uncompiled ES6 code.

In order for Jest to function properly, ES6 code must be compiled beforehand.

If you refer to the Jest documentation on Testing React Native Applications, you will find a section dedicated to compiling dependencies that do not come with pre-compiled code.

To address this issue, you must inform Jest to compile react-navigation-tabs by adding it to the transformIgnorePatterns option in your Jest configuration.

For instance:

By adjusting the jest.config.js file as shown below, the problem raised by the original poster was resolved.

However, the react-native-reanimated module, which requires native integration, will require additional attention. Modules with such native requirements should be "Mocked" as per guidance in another post.

module.exports = {
  preset: 'react-native',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  transformIgnorePatterns: [
    "node_modules/(?!(react-native"
      + "|react-navigation-tabs"
      + "|react-native-splash-screen"
      + "|react-native-screens"
      + "|react-native-reanimated"
    + ")/)",
  ],
}

Important to note that while the original purpose of the transformIgnorePatterns option is to exclude files from compilation, utilizing the pattern (?!(some-dir-name|another-name)) with the negative look-ahead (?!...) explicitly instructs Jest to exclude everything within the node_modules directory except those specified.

Answer №2

As mentioned before, certain modules require transpilation while others do not. Below is a regex pattern I often use in many projects:

  "jest": {
    "preset": "react-native",
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|react-(native|universal|navigation)-(.*)|@react-native-community/(.*)|@react-navigation/(.*)|bs-platform|(@[a-zA-Z]+/)?(bs|reason|rescript)-(.*)+)"
    ]
  }

This pattern is effective for common react native components and also includes a specific package (in this case bs-platform) as an example for cases not covered by the previous patterns.

Answer №3

I encountered a similar issue while working on a React + Typescript application.

My initial mistake was specifying the jest.config.js file as jest.config.ts

I was running the application on Node v12.latest

Here is the configuration that eventually worked for me:

// jest.config.js

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  roots: ["./src"],
  transform: { "\\.ts$": ["ts-jest"] },
  testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
  globals: {
    "ts-jest": {
      tsConfig: {
        // allow js in typescript
        allowJs: true,
      },
    },
  },
};


// tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react",
    "baseUrl": "."
  },
  "include": ["src"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

// package.json
"devDependencies": {
    "@types/jest": "^26.0.5",
    "jest": "^26.1.0",
    "ts-jest": "^26.1.3"
}

Answer №4

If you're working with React Native and Expo, I encountered a similar issue but resolved it by following the guidelines in Expo's official document, Testing with Jest. To fix the problem with Expo components, I installed the jest preset jest-expo using a package manager. Then, I updated my package.json file as instructed:

"jest": {
  "preset": "jest-expo",
  "transformIgnorePatterns": [
    "node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|@sentry/.*)"
  ]
}

In addition, I also had to modify the transformIgnorePatterns regular expression by adding an exception for |.*font.* to address the challenges I faced with Expo Fonts. Although I could have been more specific, I decided to stick with what worked since I have a dislike for regex!

Answer №5

Within your configuration file (such as .babelrc.js or package.json), ensure that you have the "modules" parameter nested under the "presets" setting, with a value of one of the following options: "amd" | "umd" | "systemjs" | "commonjs" | "cjs" | "auto" | false.

For more information, you can refer to this section in the documentation.

Your configuration might look something like this:

    "presets": [
  [
    "@babel/preset-env", {
      "targets": process.env.BABEL_TARGET === 'node' ? {
        "node": 'current'
      } : {
        "browsers": [ "last 2 versions" ]
      },
      "loose": true,
      "modules": 'commonjs'
    }
  ]
]

Answer №6

For those working with react-native-web, a solution that resolved my issue was including the react-native-web preset in my jest.config.js file:

module.exports = {
transform: {
  '^.+\\.tsx?$': 'ts-jest',
},
timers: 'fake',
testPathIgnorePatterns: [
  '<rootDir>/build/',
  '<rootDir>/node_modules/',
  '<rootDir>/rndemo/build/',
],
globals: {
  'ts-jest': {
    diagnostics: {
      warnOnly: true,
    },
  },
},
preset: 'react-native-web',
}

Answer №7

After making some adjustments to my babel.config.js file, I was able to get it working. It's important to ensure that presets are placed before any other configurations.

    module.exports = {
       presets: [['@babel/preset-env',{targets: {node: 
         'current',},loose:true,},],],
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can the same form be submitted with two different actions?

I am facing an issue with a form that is supposed to submit data to 2 different pages using the POST method. After trying some javascript code, I found that one form submission works correctly while the other does not. <form id="add"> <input ...

No data being displayed or returned from API when using async await

My Ionic 6 + Angular 14 application is currently facing an issue with displaying data retrieved from an API... I have implemented a service to fetch the data from the API and then called this service in the component. The app compiles without any errors a ...

Using AngularJS to add external scripts to partials with ng-include

Why won't my main javascript files (located in index.html) work in the partials (such as page1.html)? For example, jQuery and syntax highlighting scripts are not functioning properly when I click on my menu items. HTML CODE: <div data-ng-controll ...

What are the appropriate scenarios for extending and utilizing an abstract class in Angular?

@Component({ selector: 'my-component', template: `<ng-content></ng-content>`, providers: [ { provide: AbstractClass, useExisting: forwardRef(() => TargetComponent) } ] }) export class TargetComponent extends AbstractCla ...

Encountering difficulties accessing the array in the controller through ajax

Having trouble receiving an array of data from AJAX to the controller. $.ajax({ type: "POST", url: "/Home/List", traditional: true, contentType: 'application/json', data: { "Query&quo ...

Guide to resolving the error "Type 'void' cannot be assigned to type 'Function' in VueJS"

I've created a Vue component that requires a function pointer to execute a delete action. <template> <q-card class="my-card" > <q-img :src="media.normal || media.original"> <div class="absolute ...

What is the best method for transferring properties to the parent component using Vue router?

I have a multi-step form that each step has a different header structure. The only variation in the header among the steps is the wording, which changes as you progress through the steps. I am looking for a way to achieve this using Vue Router: pa ...

Android is now asking for location permissions instead of Bluetooth permissions, which may vary depending on the version

I am currently troubleshooting a React Native application that relies heavily on Bluetooth permissions. However, I am encountering an issue with the Android platform where the Bluetooth permissions are appearing as unavailable. I have configured the permi ...

Transmitting various pieces of information using AJAX

Is it possible to send both "credit_uri" and "address" strings in one AJAX request? Currently, only the second string is being sent. How can I include both in the data of the request? $.ajax({ url: '#{add_cards_path}', type: 'POST&apo ...

Exploring the inner workings of the canDeactivate guard feature in Angular

Exploring the concept of guards in Angular has sparked a question in my mind. Why can't we simply have a class with a deactivate method that we can import and use as needed? The provided code snippets illustrate my confusion. export interface CanComp ...

Challenges encountered with autofill and a null string

When I try to fetch data from the server for autocomplete, it returns no options even though two options are displayed in the console after making an API call. The value I enter includes two empty spaces followed by 'IPH', triggering the API call ...

Maintaining a reference to an element while binding event handlers in a prototype

Is there a way to utilize a bound event handler in prototype while maintaining the "this" context? It seems that doing so disrupts the default binding provided by prototype for event handlers. According to the documentation: The handler's context ...

Display child component automatically upon parent component state update

The main component Dashboard manages the state for each ListItem added to my Watchlist. However, whenever I add an item, it is inserted into the database but only appears when I refresh the browser. class UserDashboard extends React.Component { state = ...

I've been attempting to develop a React application, but I consistently encounter the following error: "npm ERR! cb() function was never invoked!"

Here is the issue at hand: HP@DESKTOP-1HP83V8 MINGW64 ~/Desktop/Web-Development (master) $ npx create-react-app my-app A new React app is being created in C:\Users\HP\Desktop\Web-Development\my-app. Packages are being installed. ...

Is there a way to dynamically replace a section of a link with the current URL using JavaScript or jQuery?

I have a link that appears on multiple pages, and I want to dynamically change part of the link based on the current URL* of the page being visited. (*current URL refers to the web address shown in the browser's address bar) How can I use JavaScript ...

Designing websites using elements that float to the right in a responsive manner

Responsive design often uses percentage width and absolute positioning to adjust to different screen sizes on various devices. What if we explore the use of the float right CSS style, which is not as commonly used but offers high cross-browser compatibilit ...

Is it possible to pass a parameter to a PHP controller using JavaScript without relying on jQuery or AJAX?

Is it possible to achieve the task at hand? That's the main question here. My goal is to extract data from a popup window and then, upon closing it, send this extracted content to a PHP controller for further processing. I'm facing conflicts wi ...

typescript: How to restrict an array's type in a specific order

Is there a way to restrict the types of elements in an array in TypeScript without specifying paradigms? For example, instead of defining arrays as follows: const arr:Array<any> = [] I would like to be able to specify a specific order for the arr ...

What is the method to individually determine "true" or "false" using .map() in coding

I am faced with an array of data that needs to be manipulated individually, but it should still function as a cohesive unit. Can you assist me in achieving this? function OrganizeFollow() { const [followStatus, setFollowStatus] = useState([]); co ...

Counting words with JavaScript without using an input tag is a useful skill

Is there a way to count the words in a text using only p and span tags, without using input tags? How can this be achieved? <span class="word" id="word">Words Number</span> <p class="any" id="any"> ...