NextJS applications can encounter issues with Jest's inability to parse SVG images

Upon running yarn test, an unexpected token error is encountered:

 Jest encountered an unexpected token

This typically indicates that Jest is unable to parse the file being imported, suggesting it's not standard JavaScript.

By default, Jest will use a Babel config to transform files and ignore "node_modules".

Here are some possible fixes:
 • If using ECMAScript Modules, refer to https://jestjs.io/docs/en/ecmascript-modules for enabling.
 • To transform specific "node_modules" files, specify a custom "transformIgnorePatterns" in your config.
 • For custom transformations, define a "transform" option in your config.
 • To mock non-JS modules (e.g. binary assets), utilize the "moduleNameMapper" config option.

For more detailed instructions and examples regarding config options, visit:
https://jestjs.io/docs/en/configuration.html

Details:

/home/marouane/projects/manage-landing-page/jest.setup.ts:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import "@testing-library/jest-dom/extend-expect";
                                                                                         ^^^^^^

SyntaxError: Cannot use import statement outside a module

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)

After research, it was found that installing jest-svg-transformer is required.

The necessary lines were added to the jest.config.js file:

module.exports = {
  setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
    '^.+\\.svg$': 'jest-svg-transformer',
  },

};

Despite these efforts, the issue persisted even after trying other solutions available online.

Assistance would be greatly appreciated! Thank you!

edit:

It appears that replacing jsx with tsx in the jest.config.js file resolved the problem... A simple oversight indeed! Oh well!!!

Answer №1

I encountered the same issue and found a solution that worked for me. I recommend inlining your files to resolve it. In my jest.config, I made use of a check for .svg files and replaced them with an inline string.

// jest.config.js
module.export = {
  transform: {
    '^.+\\.[tj]sx?$': 'babel-jest',
    '^.+\\.svg$': '<rootDir>/svgTransformer.js',
  }
}
// svgTransformer.js
module.exports = {
  process(src, filename) {
    const assetFilename = JSON.stringify(path.basename(filename));

    if (filename.match(/\.svg$/)) {
      // Generating component name based on SVGR logic:
      const pascalCaseFilename = pascalCase(path.parse(filename).name);
      const componentName = `Svg${pascalCaseFilename}`;
      return `const React = require('react');
      module.exports = {
        __esModule: true,
        default: ${assetFilename},
        ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
          return {
            $$typeof: Symbol.for('react.element'),
            type: 'svg',
            ref: ref,
            key: null,
            props: Object.assign({}, props, {
              children: ${assetFilename}
            })
          };
        }),
      };`;
    }

    return `module.exports = ${assetFilename};`;
  },
};
// pascal-case.ts
import { camelCase, toUpper } from 'lodash';

export const pascalCase = (str: string) => camelCase(str).replace(/^(.)/, toUpper);

If you need any further clarification, feel free to ask.

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

Vercel Build Issue: It appears that the settings you are utilizing are intended for the 'client' module of '@sanity/preview-kit'

Hey there, I'm encountering a strange issue with Vercel deployment related to sanity. The specific error message during the Vercel build is: Error: It appears that you are using settings intended for '@sanity/preview-kit/client', such as &a ...

Setting up Material-UI for React in conjunction with Typescript: A step-by-step guide

I've encountered issues while trying to integrate Material UI into my React project that's written in Typescript. Following the tutorial, I began by adding the react-tab-event-plugin. import injectTapEventPlugin from 'react-tap-event-plugi ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...

Ways to stop dialog from disappearing in Reactjs

This code snippet demonstrates the implementation of a popup with buttons, where clicking the cancel button triggers a confirmation dialog. To make the popup disappear when clicked outside of it, the following event handling is employed: const popupRef = ...

What are some alternatives to using fetch for making API calls in Next.js?

In my NextJS project, I have an express backend where data fetching is required in getServerSideProps. The issue arises when using await fetch('/api/anyApi'), as it does not work with relative paths, and calling to the absolute path await fetch( ...

Angular2: Once user is authenticated, navigate to specific routes

I've developed an admin panel with a router for page navigation. The layout of the admin panel includes a sidebar (Component), header (Component), and content (Component). Within the content, I have inserted <router-outlet></router-outlet> ...

bundle.js encountered a TypeError when attempting to read a property that was undefined, specifically while trying to access the PriceIndexationDataControlStandard

In the midst of developing a React component using the Microsoft PCF Framework, I encountered a perplexing error seemingly out of the blue. While making changes in TypeScript without even executing any build commands, the rendering of my component suddenly ...

Maximizing the potential of typescript generics in Reactjs functional components

I have a component within my react project that looks like this: import "./styles.css"; type InputType = "input" | "textarea"; interface ContainerProps { name: string; placeholder: string; as: InputType; } const Conta ...

Unable to modify the theme provider in Styled Components

Currently, I am attempting to customize the interface of the PancakeSwap exchange by forking it from GitHub. However, I have encountered difficulties in modifying not only the header nav panel but also around 80% of the other React TypeScript components. ...

What is the process for choosing nested colors from a theme in Material UI?

I have a question regarding how to select a nested style from my theme when creating a Button. Below is the snippet of code that illustrates my dilemma: const buttonStyle: SxProps<Theme> = { '&:hover': { backgroundColor: 'bac ...

The alias for the computed column is not correctly connected to the TypeORM Entity

I am currently working on extracting data from a table in a MySQL database using TypeORM for my Express.js project. In order to retrieve the data, I am utilizing the QueryBuilder. This is the implementation I have: const result = await this.repository.cr ...

Insert analytics code post-button click permission granted in Next.js/React

Need help with activating analytics scripts upon a button click? I have analytics scripts that I want to add to my next.js website only if the user opts in. When a button in my CookieBanner component is clicked, a cookie is set to track if the user has o ...

A step-by-step guide to implementing a sleek black separator line in your Next.js project with Tailwind CSS

Looking for some advice on adding a thin black line between the "NEXT" button and the text below on the Prada register page. Any suggestions? Check out the Prada register page here ...

Exploring the JSON Array in Angular5 with the power of ngFor

Currently, I am working on a project using Angular5 and encountering an issue with the *ngFor directive. The model class I have defined looks like this: export class FetchApi { value: Array<String>; api_status: string; api_version: string; d ...

Dynamic Assignment of Object Values Based on Enum Keys in Typescript

Check out this TS Playground for this piece of code. Dynamically Assigning Object Values Based on Enum Key I am attempting to achieve the following: in the interface iAnimals, each animal key in the enum Animals should have its associated interface value, ...

Is there a way to keep a button in a "pressed" state after it has been clicked?

Could someone kindly share the code with me? I am looking for a button that remains pressed after clicking it. At times, I feel embarrassed for struggling with seemingly simple tasks. Grateful for any guidance or solution provided by this community! Man ...

Identified the category

How can I retrieve the default option from a list of options? type export type Unpacked<T> = T extends Array<infer U> ? U : T; interface getDefaultValue?: <T extends Option[]>(options: T) => Unpacked<T>; Example const options = ...

Carousel Alert: Ensure that every child within the list is assigned a distinct "key" property

I'm experiencing an issue that is proving to be more challenging than usual, as it appears to be related to a specific library. I understand that using a key from a file is not ideal, but the plan is for it to come from a database in the future. Libr ...

Why is it that the resource fails to load in an Angular localhost environment when making an http request?

In the realm of ASP.NET MVC projects lies my creation, a masterpiece utilizing Angular UI components powered by ASP.NET WebAPI. As an explorer navigating the unknown territory of Angular, I present to you the sacred texts residing within my project. Behol ...

Tips for concealing tick labels in d3 using TypeScript

When trying to hide tick labels by passing an empty string to the .tickFormat("") method, I encountered an issue with Typescript. The error message received was as follows: TS2769: No overload matches this call. Overload 1 of 3, '(format: null): Axi ...