我有以下中间件:
function check(expectedKeys: string[], req: Request): boolean{
if (expectedKeys.length !== Object.keys(req.body).length) return false;
for (const key of expectedKeys) {
if (!(key in req.body)) return false;
}
return true;
}
export default function checkRequestBodyKeys(expectedKeys: string[]) {
return (req: Request, res: Response, next: NextFunction) => {
const isValid = check(expectedKeys, req);
if (isValid) return next();
return res.status(Status.BadRequest).json({status: Status.BadRequest, error: ErrorMessage.InvalidRequestBody});
}
}
我这样调用它:
import { Router } from "express";
import postAuth from "../controllers/auth.controller";
import checkRequestBodyKeys from "../middlewares/checkRequestBodyKeys.middleware"
export const authRoute = Router();
authRoute.post("/", checkRequestBodyKeys(["email", "password"]), postAuth);
我想测试它是否返回了预期的值(res和next的参数)。我知道如何测试和模拟简单中间件的函数,但对于这种类型,我不知道如何实现。
我正在尝试写这样的代码,但我知道这没有任何意义:
describe("validateRequestBody middleware", () => {
let mockRequest: Partial<Request>;
let mockResponse: Partial<Response>;
let nextFunction: NextFunction = jest.fn();
beforeEach(() => {
mockRequest = {};
mockResponse = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
};
});
test('short name should return error', async () => {
const expectedResponse = [{error: "Invalid name"}];
mockRequest = {
body: {
name: "aa",
email: "test@yahoo.com",
password: "###!!!AAAbbb111222"
}
}
const check = checkRequestBodyKeys(
["name", "email", "password"]
);
expect( checkRequestBodyKeys(["name", "email", "password"]) ).toEqual(Function)
});
});
有人可以帮我解决这个问题吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
checkRequestBodyKeys返回一个函数,该函数是express使用的实际中间件。返回的函数必须使用模拟的req、res和next执行。然后,您可以检查它们或其中的函数是否以您期望的参数被调用。
describe("validateRequestBody middleware", () => { let mockRequest: Partial;
let mockResponse: Partial;
let nextFunction: NextFunction = jest.fn();
beforeEach(() => {
mockRequest = {};
mockResponse = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
};
});
test('short name should return error', async () => {
const expectedResponse = {status: 400, error: "Invalid name"};
mockRequest = {
body: {
name: "aa",
email: "test@yahoo.com",
password: "###!!!AAAbbb111222"
}
}
const check = checkRequestBodyKeys(
["name", "email", "password"]
);
expect( check ).toEqual( expect.any(Function) )
// The middleware is called
check(mockRequest, mockResponse, nextFunction)
// And here you check if the res.json function was called with certain parameters
expect( mockResponse.json ).toBeCalledWith(expectedResponse)
});
});