Mocking a dependency in Jest that is initialized prior to exporting the module

I'm currently in the process of testing a file that exports a single default function and also needs to create an object prior to exporting the function. It's crucial for this object to remain constant and be the same instance every time the exported function is invoked.

Below is a simplified version of the module:

import { HttpClient } from '../client'

const client = new HttpClient()

export default (params) => {
    const url = 'www.'
    // Additional code here to generate URL based on passed params
    return client.get(url)
}

The objective is to verify that the URL sent to the client.get() function is accurate, which brings us to the test case below:

import myModule from '../myModule'
import { HttpClient } from '../client'
jest.mock('../client')

const mockHttpClient = { get: jest.fn(() => 'test') }
HttpClient.mockImplementation(() => mockHttpClient)

it('should parse the query param string', () => {
    console.log(myModule({}))
})

During test execution, the response from myModule({}) consistently comes back as undefined.

However, if I relocate the const client = new HttpClient() line within the exported function itself, everything functions correctly, and myModule({}) returns test.

It's imperative for the HttpClient to only be instantiated once and maintain the same instance upon each function call, emphasizing the need for it to be created outside the function. Is there a way to mock this object creation process to return my desired value? Your assistance is greatly appreciated.

Answer №1

It is important to note that the reason behind this behavior is due to the fact that when you execute import {} from '../client', it triggers the immediate instantiation of new HttpClient() before you have a chance to mock the constructor. To address this issue, you can modify your mock setup as follows:

jest.mock('../client', () => ({
  HttpClient: jest.fn(() => ({
    get: jest.fn(() => 'test'),
  }));
}));

Additionally, in scenarios where network operations are asynchronous, it may be necessary to ensure that your mocked functions return promises such as

jest.fn(() => Promise.resolve('test'))
or
jest.fn().mockResolvedValue('test')
.

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

Tips for accessing the value within a function during an onClientClick event

In my ASP.NET ASPX application, I am trying to evaluate a parameter within a function during an `onclientclick` event. Additionally, I want to include `return false` in the `onclientclick` event to prevent the page from refreshing. The `onclientclick` eve ...

Encountering the error message "Uncaught Error: Objects are not valid as a React child" even though I am not passing objects as children in my React component

My current challenge involves mapping an array of objects, which I retrieved from an axios.get request and then passing them as children to React components. The error message that's causing trouble for me reads as follows: An Error occurred: Objects ...

Unique option preservation on customized HTML select menus - Maintain original selection

Currently, I am attempting to replicate a custom HTML select based on the example provided by W3 Schools. You can view the demo through this link: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select The issue I am encountering is that ...

Straightforward JSON issue

I am new to JSON and I need to work with it now. I have tried several examples from the jQuery page, but they don't seem to be working for me. I have a *.php file that generates a string. From what I understand, this is how I pass JSON data from PHP ...

Various SVG paths make up segments

I have created an intricate SVG file containing 35 different paths resembling train tracks. My next step is to break down these paths into 16 segments, allowing another SVG path (train) to smoothly traverse along them. The ultimate goal is to grant users ...

Tips for optimizing the functionality of the Angular search filter

When I type a search string in the column "Failure signature" in my code, it doesn't seem to work. The data is not filtered based on the search string provided, and an error is thrown. I have identified the line where the error occurs. I have created ...

Update the functionality of the Rotate library event

I'm attempting to incorporate this code for my animation: link to my animation My issue arises when I try to trigger the picture animation upon clicking a button, here is the HTML snippet: <form> <input type="submit" value="change" onclick= ...

Can the orientation of the card reveal be customized in Materializecss?

Exploring the card-reveal feature in the materializecss framework on this page: https://codepen.io/JP_juniordeveloperaki/pen/YXRyvZ with official documentation located at: In my project, I've rearranged the <div class="card-content"> to display ...

What is causing the duplication of Google Map drawing controls?

I've been trying to integrate the Google Maps JavaScript API into my React project to create a map with polygon drawing capabilities. The map itself is functioning perfectly fine, but I'm encountering an issue where two sets of drawing controls a ...

The API GET request is not returning any data, even though Postman is able to retrieve the

While attempting to make an API call to a remote server, I encountered the following error initially: No 'Access-Control-Allow-Origin' header is present on the requested resource. To temporarily resolve this issue, I appended the https://cors- ...

Is it possible to share a type exclusively among object properties based on the given value?

My goal is to create a custom React table component with the ability to select rows in single, multiple, or none selection modes. The current table component I am refactoring is quite large, so I want to simplify the setup and props as much as possible. I ...

When using AngularJS and Require together, there may be instances where the r.js

There seems to be a ongoing discussion about whether or not to use require.js with AngularJS, however, I have decided to implement it in my project. Currently, the project is set up and running with require, and my next step is to optimize and minify using ...

Yii2 pjax not refreshing properly when updating records in the gridview

I have successfully implemented functionality in my grid-view to control the number of rows displayed per page. This feature includes a drop-down menu with options such as 5, 10, 25, 50, and 100 rows. Whenever a user selects an option from the drop-down, I ...

Adjust the size of a textarea once text is removed

When you type text, a textarea expands in size. But what if you want it to dynamically decrease its height when deleting text? $('textarea').on('input', function() { var scrollHeight = parseInt($(this).prop('scrollHeight&apos ...

Keep sending HTTP requests until the header contains an attachment

Welcome to our web application where you can generate and download a .zip file simply by visiting the URL. I am looking to develop a Node.js application using the requestjs library that will continuously send requests until it detects an attachment header ...

What are the best practices for handling dynamic content internationalization in Angular?

According to Angular.io, the i18n tag is used to mark translatable content. It should be placed on every element tag that requires translation of fixed text. Now, what if we have an element with dynamic content? For example, consider a table displaying a ...

Efficient Ways to pass information to an Object within a nested function

const http = require('https'); exports.ip = async (req, res) => { const ip = req.body.ip; const ip_list = ip.trim().split(' '); const count = ip_list.length; var execution_count = 0; var success = {}; // **Creati ...

Issues with Angular ng-bootstrap tabset component not functioning as expected

{ "name": "ModalWindow", "version": "1.0.0", "repository": { "type": "git", "url": "" }, "scripts": { "build": "webpack --mode production", "start": "webpack-dev-server --mode development --open" }, "license": "MIT", "depend ...

Employing getters in the toObject() method

As I delve into the code of a Node.js Express application for learning purposes, I came across the following line that sparked my curiosity regarding the inclusion of getters and virtuals. var pgmsDbObj = chnnlList[chnnlIndex] var pgmsObj = pgmsDbObj.to ...

What caused the auto resize feature of the Automatic Image Montage jQuery plugin to malfunction?

Apologies in advance if my issue is a bit convoluted. I've integrated the Automatic Image Montage jQuery plugin into a page I'm currently working on. However, I seem to have disrupted the functionality that automatically resizes images when the w ...