Steps to resolve the issue of "SVG Not defined" during JEST unit testing

Currently, I am in the process of setting up a unit test case for a function within a TypeScript class. This particular class relies on svg.js. However, when attempting to run the unit test with Jest, an error is thrown stating that SVG.extend or SVG is not recognized as a function.

We have attempted different approaches in the jest.config.js file by configuring the testEnvironment to be node to jsdom.

The TypeScript code snippet looks like this: import SVG from 'svg.js';

export class DrawManager {
  private static _drawingStage : SVG.Nested|undefined;
  private static _canvas : SVG.Doc|undefined;
}

static start(div: string) {
    this._canvas = SVG(div)
    this._drawingStage = this._canvas.nested();
}

The code for the unit test is as follows:

import { DrawManager } from './drawmanager';
describe('Test for Draw Manager', () => {
    it('should execute the task loader method successfully', () => {
    DrawManager.start('drawing');
 });
});

Our goal is to have the test case pass without encountering any issues related to SVG dependencies and ensure that the test case runs smoothly with the initialized SVG class.

Your assistance in this matter would be greatly appreciated.

Answer №1

After encountering an issue, I managed to find a solution that worked for me. The key is to set up a setupFile specifically for jest, such as setupJestMock.ts.

This setup file should contain the following code:

const obj = require('@svgdotjs/svg.js');
const SVG = (arg) => {
  return obj.SVG(arg)
};

Object.assign(SVG, obj);

(global as any).SVG = SVG;

Once you have created this setup file, you need to integrate it into your jest configuration. This can be done in package.json or any other method you use to configure jest. In my case, I added it to my jest.config.json file.

"setupFiles": [
    "<rootDir>/setupJestMock.ts"
  ],

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

Getting specific numbers from a URL path using regex

Trying to extract the numbers 123456 from three different URL paths: /aaa/bbb/co1-e3ee1ddd-3333s1-123456/art-1?unitId=art(1)par(5) /aaa/bbb/cos-123456/art-1 /aaa/bbb/cos-123456?unitId=art(1) Tried using (\d+) but it matches all numbers instead. ...

How to format decimals in Typescript/Angular with a pipe: comma or dot?

I've recently developed a custom pipe and I'm looking to enhance it by adding commas or periods to thousands values. For instance, 1000 should be displayed as either 1,000 or 1.000. Here is the code snippet for my custom pipe: import { Pipe, Pi ...

Use Typescript to access and utilize the value stored in local storage by using the

Trying to retrieve the language setting from localHost and implement it in a translation pipe as shown below: transform(value: string): string {... localStorage.setItem("language", JSON.stringify("en")); let language = JSON.parse(loca ...

Testing an AngularJS controller that relies on route resolution is an integral part of the development

I am having difficulty writing unit tests for my controller because it relies on data that is fetched when the route is resolved. I need to find a way to test this without encountering errors related to missing "locals". The controller code snippet: myMa ...

Mastering the art of typing a member of an abstract generic class in Typescript with consideration for potential additional implementations

It's quite challenging to put into words, but essentially I aim to create a base abstract class outlining an abstract interface that must vary based on whether a derived class implements a specific interface or not. Here is a TypeScript playground de ...

Leverage the power of Typescript to flatten a JSON model with the help of Class

Currently, I'm exploring how to utilize the class transformer in TypeScript within a Node.js environment. You can find more information about it here: https://github.com/typestack/class-transformer My goal is to flatten a JSON structure using just on ...

Is it possible to confirm the authenticity of a hashed secret without having knowledge of the salt used

My method of storing API-Keys involves hashing and saving them in a database. ... async function createToken(userId:number) { ... const salt=await bcrypt.genSalt(15) const hash=await bcrypt.hash(token, salt) await db.store({userId,hash}) } ...

Adding and removing/hiding tab-panels in Angular 4 with PrimeNg: A step-by-step guide

I'm currently working on a tabView project with a list of tab-panels. However, I am struggling to find a way to dynamically hide and unhide one of the tab panels based on specific runtime conditions. Does anyone have any suggestions or insights on how ...

Enhance JQuery functionality using Typescript

Currently, I am in the process of developing a Typescript plugin that generates a DOM for Header and attaches it to the page. This particular project utilizes JQuery for handling DOM operations. To customize the plugin further, I aim to transmit config Opt ...

What is the best way to merge import all with different elements?

My TSLint is flagging the following issue: Multiple imports from 'moment' can be combined into one. Here is the code causing the problem: import * as moment from 'moment'; import { Moment } from 'moment'; I have attempted ...

Experiencing the error message "delete(...).then(...).error is not a function" while attempting to remove a file from Firebase storage using AngularFire and TypeScript

I'm trying to implement the code snippet from Firebase documentation to delete a file and then upload a new image in the same directory on Firebase Storage. However, I keep encountering an error message saying "delete(...).then(...).error is not a fun ...

IntelliSense in VSCode is unable to recognize the `exports` property within the package.json file

Currently, I am utilizing a library named sinuous, which contains a submodule known as "sinuous/map". Interestingly, VSCode seems to lack knowledge about the type of 'map' when using import { map } from "sinuous/map", but it recognizes the type ...

Automatically adjust padding in nested lists with ReactJS and MaterialUI v1

How can I automatically add padding to nested lists that may vary in depth due to recursion? Currently, my output looks like this: https://i.stack.imgur.com/6anY9.png: However, I would like it to look like this instead: https://i.stack.imgur.com/dgSPB. ...

What is the reason behind using `Partial<>` to enclose the Vue props?

I am currently working with a combination of technologies, and I am struggling to pinpoint the root cause of the issue. Here is the Tech Stack: Vue 3 TypeScript Vite VSCode / Volar unplugin-vue-macros (https://github.com/sxzz/vue-macros) unplugin-vue-com ...

Using href with IconButtonProps is not supported

I'm facing a challenge in creating a wrapper for the IconButton. I aim to pass components or href props, but unfortunately, I am unable to achieve this by passing the IconButtonProps. Is there a way to accomplish this? function CustomIconButton(props ...

Using VueJS along with Typescript and implementing dynamic import

Oops! I mistakenly opened an issue here https://github.com/facebook/jest/issues/8801 - it was the wrong place for it. I am currently using Vue CLI 3 with Typescript v3.4.3, and when running tests from the CLI, I encountered several issues. While running ...

The Redux Toolkit Slice is encountering an issue where it generates the incorrect type of "WritableDraft<AppApiError> when the extraReducer is

I defined my initial state as MednannyAppointments[] for data and AppApiError for error. However, when I hover over state.error or state.data in my extraReducer calls, the type is always WritableDraft. This behaviour is confusing to me. Even though I have ...

Tips for implementing a reusable instance of a class in (SSR) React (comparable to a @Bean in Spring)

I am currently developing a new application using Next.js and React (Server Components) in TypeScript. In order to showcase and evaluate the app, I need to support two different data sources that provide identical data through separate APIs. My goal is to ...

A simple method in JavaScript/TypeScript for converting abbreviations of strings into user-friendly versions for display

Let's say I am receiving data from my backend which can be one of the following: A, B, C, D Although there are actually 20 letters that could be received, and I always know it will be one of these specific letters. For example, I would like to map A ...

Understanding the significance of the term "this" in Typescript when employed as a function parameter

I came across a piece of TypeScript code where the keyword "this" is used as a parameter of a function. I'm curious to know the significance of this usage and why it is implemented like this in the following context: "brushended(this: SVGGElement) {". ...