Experimenting with express middleware without any parameters

Is there a way to test this middleware in Jest, when it requires no arguments? Most middlewares typically expect error, req, res, next parameters, but this one doesn't follow the usual pattern. I'm not sure how to even get started in testing it. It's confusing why it doesn't accept the arguments directly and instead returns them. Any guidance on how to proceed would be appreciated.

export function errorHandler() {
  return (
    error: Error,
    req: express.Request,
    res: express.Response,
    next: express.NextFunction,
  ) => {
    if ((error as any).type === 'entity.too.large') {
      error = new Error({
        errorCode: PAYLOAD_TOO_LARGE,
        message: error.message,
      });
    }

    if (!res.headersSent) {
      res.status(500).json({ success: false, errorCode: error.errorCode });
    }
    next();
  };
}

Answer №1

@jonrsharpe mentioned

testing at the integration layer.

It is known as black-box testing. This type of test only looks at the external behavior of the system, without considering the internal workings of the software. It focuses on the behavior of the software.

Perhaps you are interested in White-box testing. White Box Testing is a technique used to test software while taking its internal functioning into account.

Main Contrasts

  • Black Box Testing only looks at the external behavior of the system, while White Box Testing considers its internal functioning.
  • When performing Black Box Testing, knowledge of implementation is not necessary, unlike White Box Testing.
  • Black Box Testing generally takes less time than White Box Testing.

Below is an example of white-box unit testing:

errorHandler.ts:

import express from 'express';

export function errorHandler() {
  return (error: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
    if ((error as any).type === 'entity.too.large') {
      error = new Error(error.message);
    }

    if (!res.headersSent) {
      res.status(500).json({ success: false, errorCode: 'sys_entity_too_large' });
    }
    next();
  };
}

errorHandler.test.ts:

import { errorHandler } from './errorHandler';
import express from 'express';

describe('errorHandler', () => {
  test('should send error', () => {
    const mw = errorHandler();
    class CustomError extends Error {
      constructor(public type: string, message?: string) {
        super(message);
        this.stack = new Error().stack;
        this.name = this.constructor.name;
      }
    }
    const mError = new CustomError('entity.too.large', 'test error message');
    const mRes = ({
      headersSent: false,
      status: jest.fn().mockReturnThis(),
      json: jest.fn(),
    } as unknown) as express.Response;
    const mNext = jest.fn() as express.NextFunction;
    const mReq = {} as express.Request;
    mw(mError, mReq, mRes, mNext);
    expect(mRes.status).toBeCalledWith(500);
    expect(mRes.json).toBeCalledWith({ success: false, errorCode: 'sys_entity_too_large' });
    expect(mNext).toBeCalledTimes(1);
  });
});

Test results:

 PASS  stackoverflow/72882415/errorHandler.test.ts (10.401 s)
  errorHandler
    ✓ should send error (5 ms)

-----------------|---------|----------|---------|---------|-------------------
File             | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------------|---------|----------|---------|---------|-------------------
All files        |     100 |       50 |     100 |     100 |                   
 errorHandler.ts |     100 |       50 |     100 |     100 | 5-9               
-----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.021 s

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 is the best way to incorporate conditionals into loops when working with Jade?

I've been working on targeting a specific element within an iteration. each category in categories .menu_category p= category.category_name The code above is in Jade and it's looping through an object called categories. As I' ...

Utilizing Node.js, AngularJS, and MongoDB to build an interactive platform for online

As I ponder the compatibility of the MEAN stack (MongoDB, Express, Angular, Node) for constructing community websites, intra and/or extranet, I can't help but wonder its ideal use case. While options like Drupal and Liferay exist, I am intrigued to e ...

Verifying user identity on Android app using PassportJS

Utilizing passportjs for user authentication on my web app has worked effectively. Now, in the process of developing an Android client for the same project, I encountered an issue. Upon logging in with the local strategy on Android, successful authenticati ...

Comparison of passwords in Nodejs is hindered by Bcryptjs

Struggling to compare passwords using bcryptjs for JWT authentication. Unable to successfully verify the password during login to sign the token and send it to the client. Issue The problem arises when trying to use the .compare() method in bcryptjs and ...

Differences between Passport JWT and Passport Local SessionPassport JWT and

Currently, I am utilizing the library Express-session and Passport for authentication. I am embarking on the development of a React SPA website and grappling with establishing a secure system. The multitude of authentication methods available in Passport ...

Exploring Node.js subdomains

Currently, I am attempting to have my Node.js powered website operate on a single instance while serving multiple domains. The primary domain is example.com, and there are also subdomains such as admin.example.com and api.example.com with distinct routes, ...

Exploring the power of utilizing multiple classes with conditions in Angular 2+

Can you help me figure out how to use a condition for selecting multiple classes with [ngClass] in Angular? <td> <span [ngClass]="{ 'badge badge-success': server.type === 'PRODUCTION', 'ba ...

Reviewing for the presence of "Undefined" in the conditional statement within Transpiled Javascript code for

While perusing through some transpiled Angular code, I came across this snippet: var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { I'm puzzled by the usage of undefined in this context. Can an ...

Angular Update Component on Input ChangeEnsuring that the component is automatically

<div class=" card-body"> <div class="row"> <div class=" font-icon-list col-lg-2 col-md-3 col-sm-4 col-xs-6 col-xs-6" routerLinkActive="active" *ngFor="let subject of subjects"> <div class=" fon ...

Error Detection during Subject() Pipe Access Unit Test

I encountered an issue while writing a test case, where it is showing an error stating that pipe is not a function. The specific error message is: this.panelService.outputEmitter.pipe is not a function Below is the relevant code snippet in TypeScript an ...

Warning: The parameter type in the Node JS project is not compatible with the argument type

Upon running this code in WebStorm, I encountered a warning: Argument type {where: {email: userData.emil}} is not assignable to parameter type NonNullFindOptions<Model["_attributes"]> Can someone explain this warning to me? This project ...

Is it feasible to broaden an interface in Typescript without including a specific type?

import React from "react"; interface a_to_e { a?: string; b?: string; c?: string; d?: string; e?: string; } interface a_to_e_without_c extends a_to_e { // I want to include properties a~e except for c } function Child(props: a_to_e_without_c ...

Mongoose is having trouble connecting, but there are no errors appearing in the console

I am facing an issue with connecting my app.js to MongoDB in a new project. It was working fine previously, but now it won't connect and I don't see any console log or error message. I have double-checked the username and password multiple times. ...

The Socket.io server running on Express is currently not reachable from any external devices

I currently have a basic application using socket.io and expressjs up and running. The application is hosting a simple HTML file, which I can successfully access through my browser. However, when attempting to access it from other devices on my network, th ...

Utilizing the JavaScript Array.find() method to ensure accurate arithmetic calculations within an array of objects

I have a simple commission calculation method that I need help with. I am trying to use the Array.find method to return the calculated result from the percents array. The issue arises when I input a price of 30, as it calculates based on the previous objec ...

Error: Code layer not located while utilizing "sam invoke local" in AWS

Currently, I am engaged in an AWS project where I am developing two lambda functions. Both of these functions rely on a common codebase stored in the node_modules directory, which is placed in a separate layer named AWS::Lambda::LayerVersion, not to be con ...

Express keeps changing my 'Content-Type' header from 'application/json' to 'text/plain'

My app is built with the latest version of Express 3.x (3.18.3) and it is returning JSON data. I have included the following code to set the 'content-type' header: res.setHeader('content-type', 'application/json') However, I ...

The name is not found when using attribute, but it is found when using extends

Lately, I've encountered difficulties with creating large TypeScript modules, and there's one thing that has been puzzling me. Specifically, the following scenario doesn't seem to work: // file A.ts export = class A { } // file main.ts imp ...

Using TypeScript with Angular-UI Modals

Currently, my goal is to create a modal using angular-ui-bootstrap combined with typescript. To begin, I referenced an example from this link (which originally utilizes jQuery) and proceeded to convert the jQuery code into typescript classes. After succes ...

Error message encountered in Express.js when trying to apply the ejs function: "View is not a constructor"

I am attempting to execute certain tasks before the original app.get function is called. After referring to this page, I applied their method which worked for the most part, except when using a rendering engine. The code snippet below demonstrates what I ...