I'm completely new to testing middleware with jest
The middleware
import HttpException from "../common/http-exception"; import { Request, Response, NextFunction } from "express"; export const errorHandler = ( error: HttpException, request: Request, response: Response, next: NextFunction ) => { const status = error.statusCode || error.status || 500; response.status(status).send(error); };
The broken test giving the error TypeError: Cannot read property 'send' of undefined
import HttpException from "../src/common/http-exception"; import { NextFunction, Request, Response, response } from "express"; import { errorHandler } from "../src/middleware/error.middleware"; describe("Error handler middleware", () => { const error: HttpException = { name: "error", statusCode: 500, status: 1, message: "string", error: "string" }; let mockRequest: Partial<Request>; let mockResponse: Partial<Response>; let nextFunction: NextFunction = jest.fn(); beforeEach(() => { mockRequest = {}; mockResponse = { status: jest.fn() }; }); test("handle error", async () => { errorHandler( error as HttpException, mockRequest as Request, mockResponse as Response, nextFunction ); expect(response).toBe(500); }); });
And the typescript for HttpException
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; } }
https://stackoverflow.com/questions/65893223/how-to-test-express-middleware-error-handler-with-jest-and-typescript January 26, 2021 at 06:20AM
没有评论:
发表评论