[英]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
路由功能創建request
和response
對象的模型。
例如
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.