Using Jest to verify whether a specific class instance in JavaScript/Typescript calls a function

Currently, I am running tests on express middlewares using jest.

it("should throw 400 error if request.body.id is null", () => {
    const req = { body: { id: null } } as any;
    const res = {} as any;
    const next = jest.fn();
    myMiddleware(req, res, next);

    expect(next).toBeCalledWith(expect.any(ErrorResponse));

    expect(next).toBeCalledWith(
        expect.objectContaining({
            statusCode: 400,
            errCode: "error-0123-2342",
            message: "Field id is missing",
        })
    );
});

The ErrorResponse Class:

export class ErrorResponse extends Error {
    public statusCode: number;

    public errCode: string;

    constructor(
        statusCode: number = 500,
        errCode: string = "error-123-1993",
        message: string = "Internal Server Error"
    ) {
        super(message);
        this.statusCode = statusCode;
        this.errCode = errCode;
    }
}

I have successfully tested for specific properties in the ErrorResponse Object when called in the next function. However, I want to ensure that the ErrorResponse Object consists of only three properties (statusCode, errCode, message) even if another property like details is added to the ErrorResponse.

I aim to achieve the following and confirm that the ErrorResponse Object comprises just the 3 properties (statusCode, errCode, message).

it("should throw 400 error if request.body.id is null", () => {
    const req = { body: { id: null } } as any;
    const res = {} as any;
    const next = jest.fn();
    myMiddleware(req, res, next);

    expect(next).toBeCalledWith(
        new ErrorResponse(
            400,
            "error-3123-2332",
            "Field id is missing"
        )
    );
});

Is there a way to accomplish this in jest?

Answer №1

Upon initial inspection of the jest documentation, it appears that utilizing expect.extend might provide the functionality you are seeking:

expect.extend({
  toBeErrorResponse(received) {
    if (received instanceof ErrorResponse &&
        Object.keys(received).length === 2)
      return {
        message: () => "expected no ErrorResponse",
        pass: true,
      };
    else
      return {
        message: () => "expected an ErrorResponse",
        pass: false,
      };
  }
});
test("my ErrorResponse", () => {
  const next = jest.fn();
  next(new ErrorResponse(400, "E", "M"));
  expect(next).toBeCalledWith(expect.toBeErrorResponse());
});

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

Troubles with Angular Js: Issues with using $http.put with absolute URLs

Having an issue with $http.put in AngularJS. My server is built with Node.js and my app is in AngularJS. I am trying to make requests from AngularJS to access data on the Node.js server (same host). This code works: $http.put("/fraisforfait", elements); ...

What is the reason behind the error "Uncaught SyntaxError: Malformed arrow function parameter list" when using "true && () => {}"?

When the code below is executed: true && () => {} it results in an error message stating: Uncaught SyntaxError: Malformed arrow function parameter list Why does this happen ? Update: I am aware that wrapping the function in parentheses reso ...

Selecting Elements in AngularJS with jqLite while Excluding a Specific Element: What You Need to Know

Currently, I am in the process of developing a directive to manage a side menu within a mobile application. The menu opens smoothly with the directive I've implemented, but I am facing a challenge in selecting everything except the menu using jqLite. ...

What is the best way to retrieve the parent element in jQuery when you already have the child element selected

I am working with jQuery Mobile, which automatically generates a lot of the DOM structure. The challenge I am facing is removing radio buttons without having an id for the parent div due to the HTML construction in jQuery Mobile. While I can easily targe ...

What is a method for capturing the value of a nested input element without requiring its ID to be

Currently, I am facing a challenge in selecting the value of an input box from a user-generated ordered list of text boxes and logging its value to the console. It seems like I cannot find a way to select the value of a child's child element when the ...

How can the token be verified when authorizing Google OAuth 2.0 on the server side?

Unable to validate the user token ID on the server side despite following Google's guide at https://developers.google.com/identity/sign-in/web/backend-auth In JavaScript, I retrieve the id token and send it to the server: var googleUser = auth2.cur ...

Tips for attaching inline styles to the body element with a vuejs component

I am new to vue.js and have been learning for a couple of days now. There are still some concepts that I am struggling to understand. I am currently working on creating a dropdown menu that appears when the user clicks on three dots. However, I am facing a ...

Purging the "sessions" collections within the mongoDB MEAN stack environment

I have recently started using the Mean Stack (mean.io) app on Heroku and I've noticed that my "sessions" collection is growing significantly. Surprisingly, there doesn't seem to be a built-in method in Mean to clear it. Is there a recommended way ...

Retrieve a specific attribute from every row within an HTML table

I have an HTML table and I'm looking to extract the call_id attribute from each row using JavaScript. Here's a snippet of the table in my editor: Simplified view: https://i.sstatic.net/MlyNj.png After accessing the table using the code below, I ...

Top method for extracting mesh vertices in three.js

Being new to Three.js, I may not be approaching this in the most optimal way, I start by creating geometry like this: const geometry = new THREE.PlaneBufferGeometry(10,0); Next, I apply a rotation: geometry.applyMatrix( new THREE.Matrix4().makeRotation ...

Here's a method to extract dates from today to the next 15 days and exclude weekends -Saturday and Sunday

Is there a way to generate an array of dates starting from today and spanning the next 15 days, excluding Saturdays and Sundays? For example, if today is 4/5/22, the desired array would look like ['4/5/22', '5/5/22', '6/5/22' ...

How can we effectively implement conditional rendering when dealing with components that are nearly identical?

Depending on whether the user is a professor, student, or not logged in, I render different landing pages. The landing pages are quite similar, with the only distinction being the buttons displayed. While I could easily achieve this using inline conditions ...

Ways to implement JavaScript code in Angular 7 application

I am attempting to create a collapsible navigation bar using MaterializeCSS for mobile screens and I plan to incorporate JavaScript code into it. Can you advise where I should place this JavaScript code? Below is the snippet of code that I intend to inclu ...

Unable to assign a value to a property within a JavaScript object

I'm attempting to configure settings for a JavaScript object (my assumption is that it's not a plain JS Object, but possibly an instance of a specific class, though I haven't been able to identify the class). https://i.sstatic.net/xsUiJ.png ...

No content appearing on React screen

I initialized a fresh react project using "npx create-react-app name". After removing unnecessary files, the application no longer displays anything. I've encountered issues with react-router and defining routes as well. index.html: <!DOCTYPE html ...

What is the best way to implement an Angular application within the child routes of another Angular application?

Is it possible to load an Angular app using lazy-loading (when a specific route is hit by users) into another Angular app without compiling the first one for use in the second? This is the Routing-Module of the app to nest into an Angular app: const upgr ...

What is the best way to store JSON data in the state of a ReactJS application?

I need assistance with a data format related issue. The current format of the data is being set by someone else in the backend of the application. When the data is empty, it looks like this: "opening_time":{"Mon":[["0"],["0"]], "Tue":[["0"],["0"]], "Wed" ...

Showing Sequelize validation errors in Express API: a comprehensive guide

In my Node.js/Express API with Sequelize ORM running MySQL, I have an Organization model that enforces a 2-100 character rule under validation. When this rule is violated in the first code snippet below, the err item from the catch block in the second code ...

Choosing the default checkbox option as selected in a ReactJS application

Is there a way to preselect checkboxes in ReactJS based on certain output data? For example, I have the following output: {permission:{group:["can_view"],"topGroup":["can_update"]}} . After sending this data to the database and receiving back the edited ...

Setting the time zone for Sails.js or Express.js applications: A step-by-step guide

After creating or updating a record in Sails, the updatedAt timestamp is showing as: updatedAt: 2014-07-06T15:00:00.000Z However, I am currently in GMT+2 hours (during this season) and updates are actually being performed at 16:00. I am experiencing the ...