NodeJS 如何用Typescript和Mocha库实现表情模拟

yhived7q  于 2023-01-30  发布在  Node.js
关注(0)|答案(1)|浏览(141)

如何使用带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.
强制使用“未知”类型是解决此问题的唯一方法吗?

4xrmg8kj

4xrmg8kj1#

您可以使用node-mocks-http包为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类型,其泛型参数受Request类型约束,Request类型是MockRequest类型的子集,因此与Request类型匹配。

相关问题