如何对接收参数的中间件进行测试?
P粉548512637
P粉548512637 2023-09-07 18:39:45
0
1
598

我有以下中间件:

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)
  });
});
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板