Are undefined Static Properties an Issue in Mocked Classes? (Jest)

Currently, I am facing a challenge in mocking a class that includes a static property.

jest.mock("../../src/logger/index");
import { Logger } from "../../src/logger/index";

// ..

const LoggerMock = Logger as jest.MockedClass<typeof Logger>;

expect(LoggerMock).toHaveBeenCalledWith(Logger.level.WARN);

// ..

Despite successfully mocking the Class, the static property level is returning undefined. ->

TypeError: Cannot read property 'WARN' of undefined

-> Can anyone provide guidance on how to effectively mock a class with a static property?

Thank you

Answer №1

Firstly: Remember, Jest's expect only functions within it/test blocks

Additionally, it seems you are anticipating the invocation of Logger, but keep in mind that Logger is a class. You should anticipate the calling of a function with corresponding arguments.

Here is an example:

// Logger.ts
export class Logger {
  static WARN() {
    // perform actions
  }
}

// Logger.spec.ts
import { Logger } from './Logger';

jest.mock('./logger');

const LoggerMock = Logger as jest.MockedClass<typeof Logger>;

it.only('should function correctly', () => {
  LoggerMock.WARN();

  expect(LoggerMock.WARN).toHaveBeenCalledWith();
});

This configuration has proven effective for me

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

Struggling to locate the correct setup for .babel and react-hot-loader

I am currently utilizing babel 7. In their documentation, they specify that the new naming convention for plugins should include the @babel/ prefix. The recommended React-hot-loader babelrc configuration is as follows: { "plugins": ["react-hot-loader/ ...

What is the syntax for declaring a variable as a string or a function with parameters?

Is it possible to define a variable in TypeScript like a string or as a Function, but with specific parameters? I am aware of how to define a string actionGetData: string; and a function actionLoaded?(event: any, ui: any): void;, but when I try to define ...

Selecting a main node using the key value

Is there a way to select the root node of a d3.hierarchy based on a specific JSON key value? For instance, instead of having "A1" as the root node in the given JSON object, can we make "B1" the root node by referencing its name value? { "name": "A1", ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

The conditional type in TypeScript is malfunctioning

Upon finishing an article discussing conditional types in TypeScript located at: I have attempted to implement a conditional type in the following function: function convertToIsoString<T extends number|undefined>( timestamp:T ): T extends number ...

Implementing Firestore Read Limitations in a React Application

I have encountered an issue with Firebase billing based on the number of document reads. There is a daily limit of 50k reads per day in Firestore, but when I try to fetch documents in my React app, it triggers a quota exceeded error. FirebaseError: Request ...

What is the functionality of the toArray method?

var retrieveDocs = function (db, callback) { var collection = db.collection('tours'); collection.find({ "tourPackage": "Snowboard Cali" }).toArray(function (err, data) { console.log(data); callback; }) } Is there a p ...

ng-class not functioning properly when invoked

In my controller, I have the following function: $scope.menus = {}; $http.get('web/core/components/home/nav.json').success(function (data) { $scope.menus = data; $scope.validaMenu(); }).error(function () { console.log('ERRO') }); ...

Issue encountered when displaying an organized list in next.js

I have been working on rendering an array of items in descending order based on their values. Everything seems to be functioning correctly, but I keep encountering an error that reads Error: Text content does not match server-rendered HTML. whenever I tr ...

When working on my asp.net webform, I incorporated an AgreementCheckBox along with a CustomValidator. However, I encountered an issue where the error message

Code for AgreementCheckBox: <asp:CheckBox ID="AgreementCheckBox" runat="server" ForeColor="Black" Text="Please agree to our terms and conditions!" /> Code for AgreementCustomValidator: <asp:CustomValidator ID="AgreementCustomValidator" runat=" ...

Utilizing THREE.JS Raycaster with JavaScript "entities" rather than just meshes

I am facing a challenge with the Raycaster model. I grasp the concept of how it intersects meshes that can be transformed, but my issue lies in identifying when the specific instance of an object is clicked. Consider a scenario where there is a button. Th ...

Is it possible to add a click event to a table row that contains an input checkbox, without interfering with the ability to click the checkbox itself?

I have a table: <table> <tr> <td>Something</td> <td>Something Else</td> <td><input type='checkbox' value='clickme' id='yes'></td> </tr> When a user ...

Updating Previous and Next links in an Angular Table following row deletions: A step-by-step guide

I need to implement a feature where row elements can be deleted by enabling checkboxes on the rows and clicking the Delete button. Although I am able to successfully delete items from the table upon clicking the Delete button, I am facing challenges in upd ...

Obtain the final value within a URL's path segment

If we have an href similar to: http://localhost:8888/#!/path/somevalue/needthis Is there a way to extract the last value in the path string (i.e., "needthis")? I experimented with window.location.pathname, but it only returns "/". Another attempt was m ...

Display pie charts on a Google Map

Utilizing a combination of JavaScript and GoogleMaps technology Within my application, there exists a screen showcasing a Google Map. In addition to this map, I have incorporated statistics detailing Population growth data displayed in the form of Pie Cha ...

Tips for preserving changes made to a jQuery script when the page is reloaded

Is there a way to retain jQuery script changes when the page is reloaded? I have a page where clicking on certain elements triggers events, and I want these changes to persist even after reloading the page, resetting only when the cache is cleared. I appre ...

What is the solution for the error "BREAKING CHANGE: webpack < 5 used to automatically include polyfills for node.js core modules"?

I am trying to use the "web3" and "walletconnect/web3-provider" package in a Vue & Laravel 8 project. I have installed it using the npm i --save web3 @walletconnect/web3-provider command and then added the following code to import into ...

Customized placement of form fields on an HTML grid determined by the user

My goal is to organize input elements on a grid based on user preferences. After researching, I stumbled upon CSS grids, which seem promising. I am considering creating a CSS grid with r rows and c columns, then using JavaScript to assign input elements t ...

The implementation of local JSON instead of external JSONP in Angular

I am exploring the option of storing a json-file on the same server as my Angular app. I am wondering about how I can modify this code to read from a locally stored json file: ergastAPI.getDrivers = function() { return $http({ method: 'GET&apos ...

Issues with AJAX junk appearing after the document element in Firefox are causing disruption

Currently, I am utilizing a page fetch script to dynamically insert a web page into a div element on my site. Let's take a look at the code. By the way, I am running this on Firefox with Kubuntu. function fetchContent(URL, divId) { req = wind ...