How to simulate a particular class from a node package using Jest mocks

In my project, I'm looking to specifically mock the Socket class from the net node module. The documentation for this can be found here.

Within my codebase, there is a class structured similar to the following...

import { Socket } from 'net';

class Foo {
    protected socket: Socket;

    constructor() {
        this.socket = new Socket();
    }

    connect() {
        const connPromise = new Promise<undefined>(resolve => {
            this.socket.connect(80, '192.168.1.1', () => {
                // Perform actions with local state

                resolve();
            });
        });

        return connPromise;
    }
}

I am currently uncertain about how to properly mock the Socket class in order to provide a mock implementation for this.socket.connect.

import { Foo } from './foo';

// Is it possible to mock the Socket Class directly?
jest.mock('net')

describe("Foo", () => {
    it('resolves on connect', () => {
        const tester = new Foo();

        expect(tester.connect()).resolves.toBeUndefined();
    })
})

Any suggestions on how to manage the implementation of the this.socket.connect method?

Answer №1

One option to try is providing a factory to the mock function:

jest.mock('net', () => ({
    Socket: function() {
        return {
            connect() {
                return 'Hello World'
            }
        }
    }
}))

(Amended as I realized that referencing outer scope functions in a jest factory may not work as intended :D)

Answer №2

Dealing with a similar issue, I encountered the need to simulate the behavior of the Resolver class within the dns module. However, in my case, the object was being instantiated within a decorator. Here's how I approached solving this:

    import {Resolver} from 'dns/promises';
    
    jest.mock('dns/promises');
    
    describe('Another scenario', () => {
        const resolverMock = jest.mocked(Resolver);
    
        it('should accomplish a certain task', () => {
            resolverMock.prototype
                .resolveCname
                .mockResolvedValue([/* specify relevant values here */]);
        });
    });

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 could be the reason for my Angular 2 app initializing twice?

Can someone help me figure out why my app is running the AppComponent code twice? I have a total of 5 files: main.ts: import { bootstrap } from '@angular/platform-browser-dynamic'; import { enableProdMode } from '@angular/core'; impor ...

ngFor is failing to show the array data, which is being fetched from Firebase

Hi there, I understand that this question has been asked frequently, but the regular solutions are not working for me. ts handleChangeFormType(formType) { this.serverData.getData('questionnaire/' + formType) .subscribe( (response: Respons ...

Submitting a form within AJAX-powered tabs (using the Twitter Bootstrap framework)

I have encountered an issue while trying to submit a form that is located within tabs. The content of these tabs is generated through AJAX. My problem arises when I submit the form - the page refreshes and loads the "default" tab, causing the PHP function ...

Using a button click to toggle the vue-ctk-date-time-picker in VueJS

Currently, I am utilizing the Vue component - https://github.com/chronotruck/vue-ctk-date-time-picker within my own component. However, I am encountering an issue where I would like to maintain the component's original functionality while having a but ...

Tips for retrieving nested data objects from a JSON API on the web

Below is the provided API link - I attempted to utilize this jQuery script in order to collect data for each state individually for my project. However, I am facing difficulties accessing the information with the code provided below. $.getJSON('http ...

What is the best way to receive several responses from a PHP file using AJAX?

My PHP file is handling 2 operations: 1. Submitting data from a form into a database table, and 2. Sending an email. I am looking to display status messages through ajax. For instance, showing "First operation done, please wait for the second" and then di ...

Having issues executing a conditional check using ng-if in AngularJS

I am attempting to verify a condition and here is how it appears: <ons-list-item ng-repeat="EventList in EventLists" ng-if="EventList.start.dateTime | DateMonth == TodayDetail"> I am encountering difficulties with this ng-if="EventList.start.dateTi ...

Enhancing visuals with THREE.js and the power of transparency through EffectComposer

I am attempting to blend texture passes in a way that preserves the alpha channel. I have experimented with several methods to achieve this. The renderer has the alpha property set to true. Renderer with various setClearColor settings. The material on th ...

Setting up paths to bypass authentication on an Express website

Currently, I am in the process of developing an application using node and express. I have implemented a passport authorization middleware for all routes as part of my highly modular approach to building the app. One challenge I have encountered is when tr ...

Updates made in MobX store are not displaying in the web browser

Why are the data changes not reflecting in the view after the api call? Here is the code snippet that might help: store.js import axios from 'axios'; import {encrypt, decrypt} from '../utils/pgp.js' import {observable, action, compute ...

Modify the button input value within a PHP script

I am currently working on a piece of code that involves following different users and inserting values from a MySQL table. <td align="center"> <input type="button" name="<?php echo $id; ?>" id="<?php ech ...

An error message indicating that the page is currently being unloaded has appeared

While working on a NodeJS-ReactJS Isomorphic App, I encountered an issue when clicking on a Link. An error message popped up saying: Uncaught (in promise) Error: Request has been terminated Possible causes: the network is offline, Origin is not allowed by ...

The image code is not recognizing the image source

In my attempt to dynamically set the image source in an HTML element after creating it with JavaScript, I have made some interesting observations through testing and alert messages: When providing the image src as a fixed filepath during the creation o ...

Tips for binding to a single input box within an ngFor loop

Can anyone lend a hand with some code? I'm working on a straightforward table using ngFor, but I'm facing an issue with input binding. The problem is that all the input fields generated by ngFor display the same value when typing. How can I preve ...

Is dividing a website into two parts acceptable?

In the process of creating a social network, one major concern is making sure that the content is easily readable by Google while also providing users with a seamless and engaging experience through Ajax support. However, it's well-known that Ajax and ...

An error was encountered because it was unable to read properties of undefined, specifically in trying to access 'navigate'

Just diving into the world of react native and react navigation, I encountered this puzzling error. Uncaught TypeError: Cannot read properties of undefined (reading 'navigate') I'm scratching my head because I am using the exact same code ...

Performing mathematical operations in JavaScript, rounding to the nearest .05 increment with precision up to two

Apologies in advance. After reviewing multiple posts, it seems like the solution involves using the toFixed() method, but I'm struggling to implement it. $('.addsurcharge').click(function() { $('span.depositamount&ap ...

Transmitting information through socket.emit from the client to the server

I'm facing an issue while trying to send numeric data from the client to the server using socket.emit. The problem is that the server doesn't seem to be receiving any data, as only `null` gets logged or I might be doing something wrong in my appr ...

Angular project running Karma/Jasmine tests encounters failures when run on GitHub Action using Google Chrome on Ubuntu operating system

While working on my Angular project, I encountered an issue when trying to test it using Google Chrome with Karma & Jasmine in a GitHub Action. Google Chrome starts with multiple errors and eventually crashes after running some tests. Despite trying vario ...

Experiencing difficulties with JWT implementation and seeking to transmit the JWT token to additional APIs

I am currently working on implementing JWT authentication in node js/express js: Below is the sample code I have written for this purpose: const jwt = require('jsonwebtoken'); const secretKey = crypto.randomBytes(64).toString('hex'); c ...