Home > OS >  Testing express middleware with no arguments
Testing express middleware with no arguments

Time:07-07

How do I test such middleware with no arguments in Jest? Every middleware I found takes error, req, res, next but not in the way below middleware does. No idea how to even start with something wrong to show anything. I don't quite understand why it returns the error, req, res, next and not accept it as arguments. If you could point me in the right direction at least that would be great.

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();
  };
}

CodePudding user response:

@jonrsharpe said

test at the integration layer.

It's black-box testing. The Black Box Test is a test that only considers the external behavior of the system; the internal workings of the software are not taken into account. It is the behavior testing of the software.

I think you are looking for White-box testing. The White Box Test is a method used to test software taking into consideration its internal functioning.

Key Differences

  • Black Box Test only considers the system's external behavior, while White Box Test considers its internal functioning.
  • Implementation knowledge is not required when applying Black Box Testing, unlike White Box Test.
  • It takes less time to perform a Black Box Testing than a White Box Testing.

Whilte-box unit testing example:

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 result:

 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
  • Related