Ways to resolve the issue of Jest encountering an unexpected token

I have set up all my Jest configurations with Babel, but I am unable to run the tests as it keeps showing the same error. My project is using Next.js and TypeScript along with styled-components.

FAIL src/components/Main/main.spec.tsx
● Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file due to non-standard JavaScript syntax or incorrect configuration. By default, Jest supports Babel for transforming files based on your Babel setup.

If you are trying to use ECMAScript Modules, refer to https://jestjs.io/docs/ecmascript-modules.
For TypeScript setup, see https://jestjs.io/docs/getting-started#using-typescript.
To transform files in the "node_modules" folder, specify custom "transformIgnorePatterns" in your config.
For mocking non-JS modules, use the "moduleNameMapper" config option.

More details and examples of custom transformations can be found in the docs:
https://jestjs.io/docs/configuration
For custom transformations, visit:
https://jestjs.io/docs/code-transformation

Details:

C:\teste next\mks-sistemas\public\assets\cartImage.png:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){PNG


SyntaxError: Invalid or unexpected token

  1 | import React from "react";
  2 | import * as S from "./styles";
> 3 | import iconCart from "../../../public/assets/cartImage.png";
    | ^
  4 | import Image from "next/image";

Snapshots: 0 total Time: 3.841 s Ran all test suites. error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.enter image description here

Despite following multiple configuration tutorials, none of them seem to work for me. It seems like Jest is encountering errors from pages containing SVGs, even though I have specified the test folder correctly.

Answer №1

Make sure to update your jest.config file as shown below and install the necessary packages

npm i jest-environment-jsdom tsconfig-paths-jest

const nextJest = require('next/jest');
const tsconfig = require('./tsconfig.json');
const moduleNameMapper = require('tsconfig-paths-jest')(tsconfig);

const createJestConfig = nextJest({
  // Specify the path to your Next.js application to load next.config.js and .env files in the testing environment
  dir: './',
});

// Include any custom configurations to be passed to Jest
const customJestConfig = {
  

  setupFilesAfterEnv: ['<rootDir>/setupTests.ts'],

  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
  bail: true,
  logHeapUsage: true,
  testTimeout: 120000,
  forceExit: true,
  collectCoverage: true,


  coverageProvider: 'v8',
  collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
  moduleNameMapper,
  
};


module.exports = createJestConfig(customJestConfig);

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

Troubleshooting: Issues with Angular 2 Dependency Injection

I am facing an issue with my angular2 application that involves a simple dependency injection, but it seems to be not working correctly. Can anyone help me figure out what might be missing? Below is the error message I am encountering: EXCEPTION: Cannot ...

Issue: Angular2 RC2 throwing an error "No provider for DirectiveResolver!" while attempting to utilize TestComponentBuilder during a unit test

I have encountered an issue while trying to test my angular2 application. Every time I import TestComponentBuilder, it throws an error: Error: No provider for DirectiveResolver! This project is written in TypeScript and uses Angular2 RC2. Below is the co ...

Leveraging String Interpolation for Retrieving Array Values in Angular2 Application

In my Angular2 application, I have implemented a functionality where I loop through a list of users and display an icon to represent each user. Now, I want to enhance the user experience by using material2's tooltip (mdTooltip) feature to display the ...

JavaScript: Navigating function passing between multiple React components

I'm currently working on a React Native application utilizing TypeScript. In my project, there is a component named EmotionsRater that can accept two types: either Emotion or Need. It should also be able to receive a function of type rateNeed or rate ...

Error TS2604: Upon importing the 'material-ui' button from one package into another

Our team is in the process of implementing a new front-end for our application by transitioning from standard react to typescript. As someone who is relatively new to development, I have been struggling with a particular issue for several days now. The set ...

Initiate asynchronous ngOnInit

Can ngOnInit() actually return a promise? I've noticed a common practice where developers use this approach and it appears to be functional. However, there is a risk with unobserved promises as they can be resolved or rejected at unexpected times, s ...

What is the proper way to call document methods, like getElementByID, in a tsx file?

I am currently in the process of converting plain JavaScript files to TypeScript within a React application. However, I am facing an error with document when using methods like document.getElementById("login-username"). Can you guide me on how to referen ...

The type 'typeof' does not contain a property called 'utm'

Currently, I am working on the front-end development of a project using Angular 10. As part of the project, I am utilizing Leaflet to showcase maps. However, there arose a necessity to install the dependency (leaflet.utm). The challenge I faced was distin ...

Creating a VPC resource in Pulumi to assign to an EC2 instance

Hey there! I'm having some trouble creating an ec2 instance with the vpc attached to it. Any help would be appreciated! import * as pulumi from "@pulumi/pulumi"; import * as aws from "@pulumi/aws"; const myVpc = new aws.ec2.Vpc(&q ...

A guide on resolving a promise and retrieving the data from a fetch request

I'm struggling to retrieve a string value from a Promise after using .then on a fetch call. The scenario involves accessing a public API and extracting the rates property from the JSON response. { "base": "EUR", "rate ...

Showing upcoming dates in an ion-datetime field within an Ionic app

I'm encountering an issue while setting up an ion-datetime input field in my Ionic 4 application. The problem I'm facing is that only the current and past dates are visible, whereas I need to display future dates as well for a "To Do" form. How c ...

Exploring the process of obtaining a URL using getStaticPaths in Next.js

I am facing difficulty getting the URL in getStaticPath export const getStaticPaths = async (props) => { if (url === 'blah') { return { paths: [ { params: { pid: "create" } }, ], fallback: true, }; ...

"The issue with implementing a background image in Next.js and Tailwind CSS has not been resolved

I'm in the process of creating a dynamic carousel, but I'm encountering an issue with setting the background image. Initially, I attempted the following method: <div className={`hero h-[75vh] bg-[url('http://domainname.com.bd/${props.mai ...

What's preventing me from utilizing Leaflet Map on Next.js despite attempting Dynamic Import?

When using Leaflet, it requires the global window object which is not available on SSR (Server-Side Rendering) and can cause an error stating "window is not defined". I have tried extensively to find a solution, and the only method I found was to use dyna ...

Utilizing StyleFunctionProps within JavaScript for Chakra UI Enhancements

I need help figuring out how to implement StyleFunctionProps in my Chakra UI theme for my NextJS project. The documentation on Chakra's website provides an example in Typescript, but I am working with Javascript. Can someone guide me on adapting this ...

Determine the general type of a different type

Imagine I have the following scenario : const sub = new Subject<{ id: string; value: string; }>(); Is there a method to obtain the generic type assigned to the Subject object? const item: ??? = { id: '1', value: 'value' }; Alth ...

Validating Input Field with Regular Expression in JavaScript/TypeScript to Avoid Starting with Zero

I need to create a RegEx for a text field in Angular / TypeScript that limits the user to inputting only a 1-3 digit number that does not start with 0. While it's straightforward to restrict input to just digits, I'm struggling to prevent an inpu ...

What is the best way to set a boolean value for a checkbox in a React project with Typescript?

Currently, I am working on a project involving a to-do list and I am facing an issue with assigning a boolean value to my checkbox. After array mapping my to-dos, the checkbox object displays 'on' when it is unchecked and a 'Synthetic Base E ...

Issue with locale being undefined in NextJS Internationalization (i18n) Routing

Currently, I am delving into the realm of Next.js Internationalization (i18n) Routing for my personal website. Despite my efforts, the values for locale, locales, and default locale are displaying as undefined. (I am working with the most recent version of ...

Managing Angular subscriptions to prevent memory leaks when making API requests

When I first delved into Angular, a colleague suggested using take(1) for API calls with observables in RxJs, claiming it automatically unsubscribes after one call. Believing this, I continued to use it until noticing significant rendering delays when nav ...