簡體   English   中英

如何使用 Typescript 和 Mocha 庫模擬 express

[英]How to mock in express with Typescript and Mocha library

如何使用帶有 Typescript 的 express 在 Mocha 中模擬“請求”? 當前解決方案如下:

describe("Authorization middleware", () => {
  it("Fails when no authorization header", () => {
    const req = {
      get: () => {
        return null;
      },
    };
    expect(isAuth(req as Request, {}, () => {}));
  });
});

我有一個錯誤Conversion of type '{ get: () => null; }' to type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Conversion of type '{ get: () => null; }' to type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

強制“未知”類型是解決此問題的唯一方法嗎?

您可以使用node-mocks-http package 為express路由功能創建requestresponse對象的模型。

例如

import { expect } from "chai";
import {Request, Response} from 'express';
import httpMocks from 'node-mocks-http';

const isAuth = (req: Request, res: Response) => {
  // your code under test
}

describe("Authorization middleware", () => {
  it("Fails when no authorization header", () => {
    const req = httpMocks.createRequest();
    const res = httpMocks.createResponse()
    expect(isAuth(req, res));
  });
});

httpMocks.createRequest() API 的返回值是MockRequest類型,其泛型參數受 express Request類型約束。 Request類型是MockRequest類型的子集,因此它與Request類型匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM