The Jest test encounters failure when attempting to use an absolute path to load an SVG image

Currently, I am developing a Typescript React application using Vite. To test my app, I have implemented Jest and babel. An important aspect of my setup is the use of absolute paths throughout the entire application.

Interestingly, when I run tests with relative paths for images, they pass successfully. However, when I switch to absolute paths for SVG files, the tests fail.

Examining my Jest configuration:

module.exports = {
  testEnvironment: 'jest-environment-jsdom',
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
    '^@api(.*)$': '<rootDir>/src/api$1',
    '^@assets(.*)$': '<rootDir>/src/assets$1',
    '^@components(.*)$': '<rootDir>/src/components$1',
    '^@hooks(.*)$': '<rootDir>/src/hooks$1',
    '^@interfaces(.*)$': '<rootDir>/src/interfaces$1',
    '^@layouts(.*)$': '<rootDir>/src/layouts$1',
    '^@pages(.*)$': '<rootDir>/src/pages$1',
    '^@routes(.*)$': '<rootDir>/src/routes$1',
    '^@store(.*)$': '<rootDir>/src/store$1',
    '^@utils(.*)$': '<rootDir>/src/utils$1',
    // For svg images transformer
    '^.+\\.svg$': 'jest-svg-transformer',
  },
  setupFilesAfterEnv: ['./jest.setup.ts'],
};

Regarding my Vite configuration:

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
      '@api': path.resolve(__dirname, './src/api'),
      '@assets': path.resolve(__dirname, './src/assets'),
      '@components': path.resolve(__dirname, './src/components'),
      '@hooks': path.resolve(__dirname, './src/hooks'),
      '@interfaces': path.resolve(__dirname, './src/interfaces'),
      '@layouts': path.resolve(__dirname, './src/layouts'),
      '@pages': path.resolve(__dirname, './src/pages'),
      '@routes': path.resolve(__dirname, './src/routes'),
      '@store': path.resolve(__dirname, './src/store'),
      '@utils': path.resolve(__dirname, './src/utils'),
    },
  },
  ...

My TypeScript configuration is as follows:

    "baseUrl": "./src",
    "paths": {
      "@api/*": ["api/*"],
      "@assets/*": ["assets/*"],
      "@components/*": ["components/*"],
      "@hooks/*": ["hooks/*"],
      "@interfaces/*": ["interfaces/*"],
      "@layouts/*": ["layouts/*"],
      "@pages/*": ["pages/*"],
      "@routes/*": ["routes/*"],
      "@store/*": ["store/*"],
      "@utils/*": ["utils/*"]
    }

Finally, the component where I encounter the issue:

import loginIcon from '../../assets/images/privacy.svg';  //passes
import loginIcon from '@assets/images/privacy.svg'; //fails

...
  <Box height={64} width={64} mb={4}>
    <img src={loginIcon} width='64' height='64' />
  </Box>

The reason behind this behavior is still unknown to me. It may be related to the functionality of jest-svg-transformer. I am puzzled by why it fails with absolute paths.

Answer №1

The issue at hand lies with the configuration of your moduleNameMapper setting for @assets, as it is currently resolving to <rootDir>/src/assets$1 instead of the expected jest-svg-transformer specified in your jest.config.js.

To resolve this problem, consider adding an alias for

'^@assets/images(.*)$': 'jest-svg-transformer'

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

React component not displaying any content due to ternary operator condition being met with variable equal to 0

Seeking to display a React component upon clicking another component. When clicked, I assign the eventKey of the component to a savedId in order to render the corresponding data from the array at that index. Click Action <ListGroup> {data.map((it ...

Using the HERE Maps JavaScript API to implement custom styles from a JSON file

TLDR: How can I change the map style using a .json file from HERE maps editor? After creating a "custom" style in the new HERE map style editor and exporting it as a single .json file, I encountered difficulties applying this styling due to lack of clear ...

Error: Unable to convert null or undefined to an object | NextAuth

Recently, I've been attempting to implement a SignIn feature with Nextauth using the following code: import { getProviders, signIn as SignIntoProvider} from "next-auth/react"; function signIn({ providers }) { return ( <> ...

Introducing a delay in an observable causes incomplete data to be received in Angular using rxjs

Currently, I am facing an issue in my code where I am trying to introduce a delay using timer(500). However, the problem is that it is only returning partial data. Instead of the expected 17 fields, it is only returning 2 fields. Below is my code snippet f ...

Subtracting Arrays Containing Duplicates

Imagine having two arrays defined like this: const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr'] const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa&ap ...

The ngFor directive encounters issues when placed within a quotation mark or when used within a Bootstrap Tooltip Tag

.HTML File : I encountered an error saying, "Identifier 'mg' is not defined." However, {{mgr[0].value}} works <button type="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="bottom" ...

Could Typescript decorators be used as mixins?

In the process of developing a complex Angular2 application, I have created a base class that serves as the foundation for my components: export abstract class ReactiveComponent implements OnInit, OnDestroy, AfterViewInit { abstract ngOnInit(): void; ...

The issue with IONIC/Angular lies in its inability to properly render the JSON data retrieved

I have recently started learning IONIC/Angular and Javascript, although I do have some background in other programming languages. The issue I'm currently facing is related to fetching JSON data from an external API (I've created the API with Stra ...

Disable the functionality of the device's back button to prevent it from going back to the

For my project, I utilize popups to display important information to the user. When a popup is displayed, how can I override the functionality of the device's back button so that instead of navigating to the previous route, it will close the popup? ...

Issue with React/Next.js input field rejecting commas

I'm experiencing a problem with an input field in my React application that was developed using Next.js. The issue arises specifically when using an iPad device, where the input field behaves inconsistently when dealing with commas. When using deskto ...

Generating an Observable that connects with a pre-existing function

Currently, I've been attempting to connect the onCompleteItem array function from the ng2-file-upload package with an RxJS Observable method that can be subscribed to. The function in question looks like this: onCompleteItem(item: FileItem, response ...

Contrast the differences between arrays and inserting data into specific index positions

In this scenario, I have two arrays structured as follows: arr1=[{room_no:1,bed_no:'1A'}, {room_no:1,bed_no:'1B'}, {room_no:2,bed_no:'2A'}, {room_no:3,bed_no:'3A'}, {room_no:3,bed_no:'3B ...

Using the useStaticQuery hook outside of a function component is not allowed and will result in an invalid hook call error. Remember to only call

I am currently facing an issue while trying to retrieve values using useStaticQuery from my gatsby-config.js file. Below are snippets of my code. Does anyone have any suggestions on how to resolve this problem? Thank you in advance. Repository: https: ...

Injection of environmental variables into app services

Through the use of Nx, I have created multiple apps that each have their own environment with different API URLs. The Nx Workspace library includes shared services that are utilized among all apps, however, it is necessary to pass the environment-api-url w ...

What is the process for applying this specific style to a certain element?

Here is an example of an element in an Angular2 app: <div class="ticket-card" [ngStyle]="{'background': 'url(' + ticketPath + ')' , 'background-size': 'cover'}"> I would like to enhance the style b ...

During server-side rendering, the imported component styles from the library are not being applied

I have encountered a problem where the styles of a component from my component library, bundled with webpack 5, are not being applied during server-side rendering (SSR). I am working on two projects: A Next.js app with Styled Components that imports a co ...

Maximizing the potential of NestJS apps with Docker

I am working on a NestJS project that consists of multiple apps structured as follows: my-project: -- apps; --- app-one ---- src ---- tsconfig.app.json --- app-two ---- src ---- tsconfig.app.json -- libs -- package.json -- etc... Within this project, I ha ...

Why isn't my event handler triggering when working with TypeScript services and observables?

I am currently working on a project in Angular 2 where I am incorporating observables and services in typescript. However, I have encountered an issue where the event handler in my observable is not being triggered. Below is the code snippet: The Service ...

What is the best way to inform the user of their login status in Angular?

As a newcomer to angularfire2, I am currently working on implementing authentication and providing the user with feedback on their login status. I am using version angularfire2": "^5.0.0-rc.4. I came across an example on this site, but I am unsure of how i ...

How can I transfer the data from a file to upload it in Angular 9 without manually typing it out?

In my Angular application, I have a functionality where users can upload two files for processing on the server. However, I am looking to add a feature that allows users to simply copy and paste the contents of the files into two textboxes instead of going ...