A guide on leveraging Jest and Typescript to mock a static field within a class

While working with Typescript and a third-party library, I encountered an issue trying to write unit tests that mock out the library. Here's an example scenario:

// Library.ts
// Simulating a third party library
export class Library {
    static code: number = -1;
}
// Consumer.ts
// Utilizing the Library in a basic manner
import { Library } from "./Library";

export function setCode(newCode: number) {
    Library.code = newCode;
}
// Consumer.test.ts
// Testing the Consumer module
import { Library } from "./Library";

jest.mock("./Library", () => {
    class Library {
        static code: number = -11;
    }

    return { Library };
});

describe("Consumer", () => {
    let consumer: typeof import("./Consumer");

    beforeEach(() => {
        jest.resetModules();
        consumer = require("./Consumer");
    });

    it("should set code properly", () => {
        consumer.setCode(3);
        expect(Library.code).toEqual(3);
    });
});

After setting the code to 3 in the test, I expected the mocked Library to be used and for Library.code to also be 3. However, it actually remains at -11 as defined in the mock factory. There seems to be something missing here, but I'm uncertain what it is.

Answer №1

Discovered a workaround by utilizing mock variables in this manner:

// Consumer.test.ts
// This is a test for the Consumer
import { Library } from "./Library";

const mockLibrary = class {
  static code: number = -11;
};

jest.mock("./Library", () => {
    const Library = mockLibrary;

    return { Library };
});

describe("Consumer", () => {
    let consumer: typeof import("./Consumer");

    beforeEach(() => {
        jest.resetModules();
        consumer = require("./Consumer");
    });

    it("should properly set the code", () => {
        consumer.setCode(3);
        expect(mockLibrary.code).toEqual(3);
    });
});

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

What is the best approach to have a method in the parent class identify the type based on a method in the child class using TypeScript?

I'm faced with a code snippet that looks like this. class Base{ private getData(): Data | undefined{ return undefined } public get output(): Data | undefined { return { data: this.getData() } } } class ...

Troubleshooting problems encountered in Nest.js due to modifications made within a service.ts file

I'm currently working on a Nest.js project and here is the content of the automobile.service.ts file: import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Car } from './enti ...

What is the most effective way to condense these if statements?

I've been working on a project that includes some if statements in the code. I was advised to make it more concise and efficient by doing it all in one line. While my current method is functional, I need to refactor it for approval. Can you assist me ...

Testing React Components with Jest: Verifying correct left alignment of an image based on input parameter

For my project, I am tasked with creating a react component that includes both an image and a text box. The two requirements for this task are as follows: The Image or Text box must be left or right aligned based on the specific needs The Image or Text bo ...

I incorporated a CSS file from another HTML document. What do you think about that?

In my work with Ionic 3 and angular 4, each HTML file is accompanied by its own CSS file. There are times when I reference a class in one HTML file that is defined in another HTML file. I have observed that this CSS class gets injected into the main.js He ...

Tips for testing screen orientation using jest and testing-library/react

While testing a component in nextJs using testing-library/react and jestJs, I encountered an error when trying to access "window.screen.orientation.type". The error message read: "TypeError: Cannot read properties of undefined (reading 'type')". ...

Do not directly change a prop's value as it will be replaced when the parent component re-renders. Use v-form instead

I'm currently in the process of developing an app using nuxt along with vuetify 2.x, and I keep encountering a specific error message: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Inste ...

Typescript - Certain implementations may eliminate the optionality of properties

After exploring multiple versions of the Omit implementation, including the one displayed by Intellisense when hovering over Omit, I'm struggling to grasp why certain implementations are homomorphic while others are not. Through my investigation, I&a ...

Verify if an object property is called with the toHaveBeenCalledWith() function in Jasmine

Recently started incorporating Jasmine into my workflow and I am trying to verify if my method was called with an object that includes a MyProperty property. Currently, my setup looks like this: expect(service['method']).toHaveBeenCalledWith(jasm ...

I am unable to process the information and transform it into a straightforward list

When using ngrx, I am able to retrieve two distinct data sets from storage. private getCatalog() { this.catalogStore.select(CatalogStoreSelectors.selectAllCatalogsLoadSuccess) .pipe( takeWhile(() => this.alive), take(1), ...

Variety of properties determined by a "type" prop, expanding variations based on a value from the interface

I am trying to enhance a type based on a value from the main interface. If the type == multiline, it will have a specific interface, and if the type == icon, it will have a different type. import React, { memo, useCallback, ReactNode } from 'react&apo ...

Issue: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor can only bind to Iterables like Arrays

I have successfully pulled data from the jsonplaceholder fake API and now I am attempting to bind it using Angular 2 {{}} syntax. However, I encountered an error that states: "Error: Cannot find a differ supporting object '[object Object]' of typ ...

The error message states that the property "user" is not found in the type "Session & Partial<SessionData>"

I recently had a javascript code that I'm now attempting to convert into typescript route.get('/order', async(req,res) => { var sessionData = req.session; if(typeof sessionData.user === 'undefined') { ...

Inefficiency in POST method prevents data transmission to MongoDB

I've developed a MERN application and now I'm testing the backend using the REST client vscode extension. This is how it looks: `POST http://localhost:4000/signup Content-Type: application/json { "email": "<a href="/cdn-cgi ...

Having difficulty retrieving the file from Google Drive through googleapis

I'm currently attempting to retrieve a file from Google Drive using the Googleapis V3, but I keep encountering an error message stating: 'Property 'on' does not exist on type 'GaxiosPromise<Schema$File>'. Below is the c ...

The android() method could not be located on the root project 'xyz' of type org.gradle.api.Project when passing [before_plugins_] as arguments

Encountering an issue while attempting to run the Nativescript Android application on my device. The error message states: Could not find method android() for arguments [before_plugins_d5qrcua3za3scd760qug60fz6$_run_closure1@5754ca71] on root project &apos ...

Is there a way to change a .pptx document into a base64 string?

Currently, I am working on a project that involves creating an addin for Office. The challenge I am facing is opening other pptx files from within the addin. After some research, I discovered that I need to use base64 for the PowerPoint.createPresentation( ...

Experiencing difficulties when conducting a Karma test on an Angular service

My examination is: 'use strict'; (function() { describe('Service: Assessment', function () { var $httpBackend; // load the service's module beforeEach(module('mean')); var AssessService; beforeEac ...

What steps should be followed to effectively incorporate Google Fonts into a Material UI custom theme for typography in a React/TypeScript project

Hey there, I'm currently working on incorporating Google fonts into a custom Material UI theme as the global font. However, I'm facing an issue where the font-weight setting is not being applied. It seems to only display the normal weight of 400. ...

Having trouble importing .task files in a Next.js project with TypeScript?

I encountered an issue when trying to import a model.task file into my App.tsx file. After training a hand gesture recognition model in Python, I exported it to a model.task file. Now, I am attempting to import this file into my Next.js + Typescript proje ...