【发布时间】:2021-04-29 18:10:45
【问题描述】:
我对用 jest 测试中间件完全不熟悉
中间件
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);
};
错误的测试给出错误 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);
});
});
还有 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;
}
}
【问题讨论】:
-
请求和响应是未定义的,你有
lets但没有任何值。 -
我希望 response 的值来自中间件,这可能吗?
-
怎么样?您直接使用(未定义的)mockResponse 调用它,任何其他值来自哪里?
-
Itried with beforeEach(() => { mockRequest = {}; mockResponse = { status: jest.fn() }; });
-
好的,请edit这个问题更新现在发生的事情。想想响应实际上是如何使用的。
标签: typescript ts-jest