这是我的中间件:
export const isLogged = () => (req: Request, res: Response, next: NextFunction) => next();
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建单元测试,但无法使用正确的类型进行模拟:
const middleware = middlewares.isLogged()
middleware(
jest.fn<Request>(), // Expected 0-2 type argument but got 1
jest.fn<Response>(),
jest.fn<NextFunction>(),
);
Run Code Online (Sandbox Code Playgroud)
这是行不通的,我已经试过express模拟该模块了,但是还没有开始工作。我该如何嘲笑他们?
Bri*_*ams 11
The first two arguments are a Request object and a Response object.
Since your code doesn't use req or res you can just pass empty objects as mocks and tell TypeScript to treat the mocks as the expected types using as:
it('should call next', () => {
const next = jest.fn();
middleware(
{} as Request,
{} as Response,
next,
);
expect(next).toHaveBeenCalled(); // SUCCESS
});
Run Code Online (Sandbox Code Playgroud)
Update
If you want to mock additional properties on Request or Response then you can simply add these to your mock object.
Your mock object will (probably) not implement the full Request or Response interface so you can either use something like Partial<Request> or Partial<Response>, or simply tell TypeScript you want "to opt-out of type-checking and let the values pass through compile-time checks" by using the type any for the mock objects:
it('should call next', () => {
const req: any = {
get: jest.fn((name) => {
if (name === 'content-type') return 'text/plain';
})
};
const res: any = {
send: jest.fn()
}
const next = jest.fn();
middleware(
req,
res,
next,
);
expect(next).toHaveBeenCalled(); // SUCCESS
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1916 次 |
| 最近记录: |