Wie teste ich Middleware, die Parameter akzeptiert?
P粉548512637
P粉548512637 2023-09-07 18:39:45
0
1
621

Ich habe folgende Middleware:

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

Ich nenne es so:

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

Ich möchte testen, ob es die erwarteten Werte zurückgibt (Parameter von res und next). Ich weiß, wie man Funktionen einfacher Middleware testet und nachahmt, aber für diesen Typ weiß ich nicht, wie ich es implementieren soll.

Ich versuche, Code wie diesen zu schreiben, aber ich weiß, dass er keinen Sinn ergibt:

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

Kann mir jemand helfen, dieses Problem zu lösen?

P粉548512637
P粉548512637

Antworte allen(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)
  });
});
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage