title: How to test express middleware error handler with jest and TypeScript
body: <p>I'm completely new to testing middleware with jest</p>
  <p>The middleware</p>
  <pre><code>import HttpException from &quot;../common/http-exception&quot;;
  import { Request, Response, NextFunction } from &quot;express&quot;;
  
  export const errorHandler = (
    error: HttpException,
    request: Request,
    response: Response,
    next: NextFunction
  ) =&gt; {
    const status = error.statusCode || error.status || 500;
  
    response.status(status).send(error);
  };
  
  </code></pre>
  <p>The broken test giving the error TypeError: Cannot read property 'send' of undefined</p>
  <pre><code>import HttpException from &quot;../src/common/http-exception&quot;;
  import { NextFunction, Request, Response, response } from &quot;express&quot;;
  import { errorHandler } from &quot;../src/middleware/error.middleware&quot;;
  
  describe(&quot;Error handler middleware&quot;, () =&gt; {
    const error: HttpException = {
      name: &quot;error&quot;,
      statusCode: 500,
      status: 1,
      message: &quot;string&quot;,
      error: &quot;string&quot;
    };
    let mockRequest: Partial&lt;Request&gt;;
    let mockResponse: Partial&lt;Response&gt;;
    let nextFunction: NextFunction = jest.fn();
  
    beforeEach(() =&gt; {
      mockRequest = {};
      mockResponse = {
        status: jest.fn()
      };
    });
  
    test(&quot;handle error&quot;, async () =&gt; {
      errorHandler(
        error as HttpException,
        mockRequest as Request,
        mockResponse as Response,
        nextFunction
      );
  
      expect(response).toBe(500);
    });
  });
  
  </code></pre>
  <p>And the typescript for HttpException</p>
  <pre><code>export default class HttpException extends Error {
    statusCode?: number;
    status?: number;
    message: string;
    error: string | null;
  
    constructor(statusCode: number, message: string, error?: string) {
      super(message);
  
      this.statusCode = statusCode;
      this.message = message;
      this.error = error || null;
    }
  }
  
  </code></pre>