Creating a mock for a class method that is utilized within an asynchronous callback – what's the best approach?

As a newcomer to Jest, I am grappling with understanding the intricacies of this testing framework. My current conundrum revolves around comprehending the behavior of ES6 class mocking within asynchronous code. For instance, consider an exported class setup like this:

//util_tests.ts
export default class Utils{
  getMemberAccounts = (): Promise<Number> => new Promise((resolve, reject) => resolve(5));
}

Next, let's examine the file we wish to test (with the targeted function being getMemberAccounts):

//test.ts
import Util from './util_test'
import logger from '../common/logger';
import _ from 'lodash';

const util = new Util();
util.getMemberAccounts().then(test =>{
  logger.info(test); // this should display mocked data
});

setTimeout(async ()=> {
  let test = await util.getMemberAccounts();
  logger.info(test); // here the mocked data does not appear, why is that so? And how can we address this issue?
}, 0);

export default class Test{
  
}

The structure of my test file is as follows:

import Util from '../src/test/util_test'
import Test from '../src/test/test'
import { mocked } from 'ts-jest/utils'

jest.mock('../src/test/util_test', () => {
  return jest.fn().mockImplementation(() => {
    return {
      getMemberAccounts: jest.fn().mockResolvedValue({
        accounts: [
          {
            id: '0zh8ap6luxoijne8qlfu1sg',
            name: 'test',
            officeNumber: '23',
            emailAddress: 'string@gmail'
          }
        ]
      }
      )
    };
  });
});

describe('Test', () => {
  let testCase: Test;

  beforeEach(async () => {
    mocked(Util).mockClear();
    testCase = new Test();
  })

  test('test-case', async () => {
    
    
  })
});

Why is it that my mocking setup fails to work within the setTimeout function? Could this be attributed to the nature of setTimeout and callbacks? How can I successfully mock the class function in such a scenario?

Answer №1

Feel free to drop your questions here if you require assistance. The issue arises when setTimeout is used to defer a function call, which Jest is not aware of once the test has concluded. To overcome this, we must mock the setTimeout timer to fulfill the value within the callback function.

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

I would love to hear your suggestions for a custom select element plugin in jQuery

After browsing multiple options online, I decided to turn to the expertise of the Stack Overflow community to ask for recommendations based on personal experience. I am specifically in search of a plugin that can substitute a select element with a custo ...

After manipulating the disabled attribute with jQuery, the input field becomes read-only

Here's an interesting issue that has come up. I have a form with multiple fields and one submit button. Initially, all fields are disabled except for the email field. There is a method in place to check for changes in the email field. Upon detecting ...

Putting a Pause on CSS Transition using jQuery

I am attempting to delay a CSS transition for an element by using a delay function, with an additional 0.2s applied to make it slide 0.2s later than the initial delay of the main wrapper. I am applying a class to give it a transition effect to slide from r ...

Issue with RadAjax not triggering after client-side event handler on initial click

When utilizing RadAjaxManager to enable ajax functionality on some WebForms controls, everything works smoothly in most cases except one particular scenario: In this case, I am encountering an issue with a LinkButton: <asp:LinkButton ID="lnkSaveButton ...

Generating forms dynamically in Vue using code

I'm looking to prompt the user to specify how many points they want to create, followed by entering coordinates for each point. One approach I attempted involved using an initial text field to capture the number of points desired, and then using a lo ...

A guide on displaying tab content using Pagination

I have a project where I am trying to create a Pagination control using tabs for JSON data obtained through an AJAX request. The goal is to display 10 data items at a time and switch between pages seamlessly. So far, I've been successful in displayin ...

The console is showing an error message that reads: "Uncaught SyntaxError:

After making changes to the function moveElement by switching its formal parameter from elementID to just element, I encountered an issue. I wanted to directly pass the DOM object from the function positionMessage to the function moveElement. However, Chro ...

Add information if the data does not exist, modify it if it does

My current project involves creating a TS3 bot using the Node.js Library from Multivit4min on GitHub. The purpose of this bot is to perform the following tasks: nick (txt) cldbid (int) clid (txt) lastChannel (int) Event #1 - When a client connects to a ...

Tips for managing a click outside of a dialog box (modal)?

My issue is that my box closes whenever I click outside of it, causing me to lose all the input data. I would like the box to only close when the cancel button is clicked. I am uncertain about what is causing it to close when clicking outside. Can anyone p ...

What is the best way to determine the number of documents in an array based on their values in MongoDB?

How can I write a query to count the number of parking spaces with the excluded property value set to false for the parking lot with _id: 5d752c544f4f1c0f1c93eb23? Currently, I have managed to select the number of parking spaces with excluded: false prope ...

Attempting to invoke a function containing a promise in Javascript

Calling the function numberOfRedeems(dealId) from another function named setUpData raises an issue where the numberOfRedeems() function, which includes a promise and returns "counter", always returns as undefined when executed within the setUpData function ...

Ways to incorporate variables into the image source attribute when using Ionic

Is there a way to include {{ }} in the src attribute of an image? I encountered an error with this code near [src] <ion-list> <ion-item *ngFor="let item of results| async"> <ion-thumbnail slot="start"> <ion-img [src]={{ it ...

Retrieve all objects of the selected value using Angular autocomplete when an option is selected

I am currently working with an autocomplete component. I am passing an array of objects and would like to retrieve all item information (option) when an option is selected, not just the field value (option.name). <form class="example-form"> ...

I'm struggling with correctly specifying the return type of a function in TypeScript

Having some trouble with the return type I defined for a function that decodes tokens using jsonwebtoken. Here's the implementation: import jwt, { decode } from "jsonwebtoken"; export const authentication = ( token: string ): { error: ...

The checkbox is not showing the check mark accurately

I am currently working on a React form where I am trying to retrieve the status of a checkbox element from local storage using the useEffect hook. const [checkbox, setCheckbox] = useState(false); useEffect(() => { setCheckbox(localStorage.getItem(&ap ...

Creating a one-to-many relationship in NestJS using TypeORM and saving data efficiently

I'm currently working on a NestJS project where I need to save an array of objects in a one-to-many relationship. The frontend provides me with the following structure: [ { "actor":"actorname", "role":"actorrole" }, { "actor":"actorname2", "role":"ac ...

How to efficiently eliminate redundant entries from an object array using JavaScript or React

I've been struggling to implement the solutions provided in this thread on removing duplicates from an array of objects. Unfortunately, I haven't found a satisfactory way to do so. In my current approach (which involves adding new iconsProps to ...

Challenges with implementing singleSelect feature in MUI-X DataGrid

Encountering an issue with the singleSelect type on the community version of x-data-grid. The problem arises when attempting to edit a row, where my singleSelect consists of the following data set. Here is how I have configured my DataGrid setup. Although ...

The Tailwind Rebuild journey never comes to a halt

I have been using Tailwind for the css in my Flask app. Everything was working fine until recently when I started experiencing issues with Tailwind. Usually, when I run a tailwind build script for my app, it updates the css if there are any changes in the ...

Issue with Angular 17 custom guard failing to function properly when used alongside a backend axios request

I am in the process of developing an Angular application that includes a protected page. To secure this page, I have implemented a custom guard: { path : 'intern', // For testing purposes (internal page) component : InternalComponent, ...