如何對接收參數的中間件進行測試?
P粉548512637
P粉548512637 2023-09-07 18:39:45
0
1
613

我有以下中間件:

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)
  });
});

有人可以幫我解決這個問題嗎?

P粉548512637
P粉548512637

全部回覆(1)
P粉745412116

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)
  });
});
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板