Using Jest and Supertest for mocking in a Typescript environment

I've been working on a mock test case using Jest in TypeScript, attempting to mock API calls with supertest. However, I'm having trouble retrieving a mocked response when using Axios in the login function. Despite trying to mock the Axios call, I haven't been successful.

Below is a snippet of my code:

auth.controller.ts

import { AxiosService } from "helpers";

export class AuthController {
    constructor() {
       ...
      // Some logic here
      this.init()
    }

    public init() {
       // Setting up a route for login
       router.post('/api/auth/login', this.login);
    }
  
    login = async function (req: Request, res: Response): Promise<void> {
        // Configuring axios call with some logic
        ...

        // Service for Axios call to a third party.
        AxiosService.call(req, res, config, "login");
    }
  }
    
    

auth.test.ts

import { AuthController } from "../../modules/auth/auth.controller";
jest.mock("../../modules/auth/auth.controller");

beforeAll(async () => {
  const auth = new AuthController();
  mockLogin = jest.spyOn(auth, "login");
});

afterAll(async () => {
  server.stop();
});

test("should give login response", async () => {
    mockLogin.mockImplementation(() => {
      return Promise.resolve({ Success: true, body: "Login" });
    });

      const response = await request(server.app)
        .post("/api/auth/login")
        .send(requestBody)
        .expect(200);

      response.body // Receiving actual server response instead of the mocked one
})
    
    

Also attempted the following code but encountered no luck:

jest.mock('../../modules/auth/auth.controller', () => {
  return { 
    AuthController: jest.fn().mockImplementation(() => {
          return {
              login: jest.fn()
          }   
      })
  }
})
            
    

Here's how my AxiosService class looks:

export class AxiosService {

  public static async call(...):Promise<void> { 
    try { 
       const { data } = await axios(...);

       res.status(200).json(data);
    } catch(err) {
       res.status(400).send(err);
     }
  
  }

}

Tried to mock the AxiosService call method as shown below:

jest.mock('../../helpers/AxiosService', () => {
  return jest.fn().mockImplementation(() => {
    return { call: () => { return {success:true, data:'mock'}} }
  })
})

However, even after mocking the Axios call, I keep receiving an error message stating "Async callback was not invoked within the 10000 ms timeout specified by jest.setTimeout".

If anyone can offer assistance, it would be greatly appreciated since I'm fairly new to the concept of mocking and may have overlooked something.

Thanks in advance

Answer №1

To ensure effective testing, it is crucial to mock every unit except the one being tested.

A timeout can occur when using Supertest if the server does not respond, especially when mocking the AxiosService. In this case, the service needs to be mocked as follows:

...
return { call: (req, res) => { res.status(200).json({success:true, data:'mock'}); }

When testing, options include either mocking the controller class with a mocked service class or testing them together with a mocked Axios instance. Since AuthController is essentially an abstraction over a simple Express handler and doesn't perform much independently, it can be approached in the following manner:

jest.mock('axios', () => jest.fn()) // at top level
...
axios.mockResolvedValue({ data: ... });
const response = await request(server.app)

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 does `(keyof FormValues & string) | string` serve as a purpose for?

Hey there! I'm new to TypeScript and I'm a bit confused about the purpose of (keyof FormValues & string) | string. Can someone please explain it to me? export type FieldValues = Record<string, any>; export type FieldName<FormValues ...

Creating type definitions for recursive functions in TypeScript

I've created a JavaScript function that continuously accepts functions(params => string) until it receives an object, at which point it resolves the final string as a concatenation of all the functions invoked over the same object passed in at the ...

Issue with toggling in react js on mobile devices

Currently, I am working on making my design responsive. My approach involves displaying a basket when the div style is set to "block", and hiding it when the user browses on a mobile device by setting the display to "none". The user can then click on a but ...

Angular's text interpolation fails to update when a value is changed by an eventListener

I am encountering an issue with two angular apps, one acting as the parent and the other as the child within an iframe. The HTML structure is quite simple: <div class="first"> <label>{{postedMessage}}</label> </div> &l ...

Create a personalized button | CKEditor Angular 2

I am currently working on customizing the CKEditor by adding a new button using the ng2-ckeditor plugin. The CKEditor is functioning properly, but I have a specific requirement to implement a button that will insert a Rails template tag when clicked. For ...

When TypeScript generator/yield is utilized in conjunction with Express, the retrieval of data would not

Trying to incorporate an ES6 generator into Express JS using TypeScript has been a bit of a challenge. After implementing the code snippet below, I noticed that the response does not get sent back as expected. I'm left wondering what could be missing: ...

Could you please explain the significance of /** @docs-private */ in Angular's TypeScript codebase?

After browsing through the @angular/cdk code on GitHub, I came across a puzzling "docs-private" comment. Can anyone explain its significance to me? Link to Code * In this base class for CdkHeaderRowDef and CdkRowDef, the columns inputs are checked for ...

Is it possible to modify the parameters of a function by utilizing a MethodDecorator without affecting the "this" value?

Consider a scenario where you need to dynamically modify method arguments using a decorator at runtime. To illustrate this concept, let's simplify it with an example: setting all arguments to "Hello World": export const SillyArguments = (): MethodDec ...

Bringing in information from a TypeScript document

I'm having trouble importing an object from one TypeScript file to another. Here is the code I am working with: import mongoose from "mongoose"; import Note from './models/notes'; import User from './models/users'; import ...

Encountered a hiccup during the deployment of an Angular application on Heroku

I've been working on deploying an Angular app called "test-app" to Heroku via GitHub and everything seems to be going smoothly, except for setting up the express routing function. I've tried different paths, but Heroku keeps throwing this error: ...

The stacked bar chart in Apex is not displaying correctly on the x-axis

Currently, I am utilizing the Apex stacked bar chart within my Angular 16 project. In this scenario, there are 4 categories on the x-axis, but unfortunately, the bars are not aligning correctly with the x-axis labels. The data retrieved from my API is as ...

What is the best way to change a timestamp into a date format using Angular?

I am struggling to convert a timestamp to the date format 'dd/MM/YYYY' but keep getting a different date format in the output. I am using syncfusion spreadsheet for this task. export-electronic.component.ts updatedata(){ this.dataApi.get ...

What is the comparable alternative to promise<void> in observables?

I've been working with Angular using TypeScript and I'm attempting to return a promise from an observable. What is the correct way to accomplish this? So far, I have tried the following: of(EMPTY).toPromise() // error: Promise<Observable<n ...

Decipher the splitButton tag from PrimeNG

I am currently attempting to translate items from "p-splitButton", but I am facing a challenge because the "items" is an object. How can I accomplish this task? [model]="items | translate" app.component.html <p-splitButton label="Save" icon="pi pi- ...

Best practice for encapsulating property expressions in Angular templates

Repeating expression In my Angular 6 component template, I have the a && (b || c) expression repeated 3 times. I am looking for a way to abstract it instead of duplicating the code. parent.component.html <component [prop1]="1" [prop2]="a ...

I'm unable to resolve all parameters for xxx -- unit testing using jest

I recently encountered an issue with a test in jest that is failing and displaying the following error message: Error: Can't resolve all parameters for LoginService: (?). at syntaxError (/Users/wilson.gonzalez/Desktop/proyecto_andes/external/npm/nod ...

Error encountered while upgrading to Angular 5: splitHash issue

Currently in the process of transitioning from Angular 4.x to 5.x, I have encountered the following error: main.81bcdf404dc22078865d.bundle.js:1 Uncaught TypeError: i.splitHash is not a function at Object.t.parseUrl (main.81bcdf404dc22078865d.bundle.js:1) ...

Unable to resolve external modules in TypeScript when using node.js

I wanted to integrate moment.js into my node application, so I proceeded by installing it using npm: npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adc0c2c0c8c3d9ed9f8399839d">[email protected]</a> J ...

Place information from an input field into a specific row within a table

Utilizing Angular 4, I am developing a frontend application for a specific project. The interface features a table with three rows that need to be filled with data from an external source. https://i.stack.imgur.com/Dg576.png Upon clicking the "aggiungi p ...

The binding to 'videoId' cannot be established as it is not a recognized attribute of the 'youtube-player' component

Currently, I am working with Ionic 3 and Angular 5. In my application, I am integrating Youtube videos using ngx-youtube-player. However, I am encountering errors: Template parse errors: Can't bind to 'videoId' since it isn't a know ...