我有以下中間件:
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) }); });
有人可以幫我解決這個問題嗎?
checkRequestBodyKeys傳回一個函數,該函數是express使用的實際中間件。傳回的函數必須使用模擬的req、res和next執行。然後,您可以檢查它們或其中的函數是否以您期望的參數被呼叫。