【发布时间】:2020-01-17 17:32:13
【问题描述】:
在 Jest 中获取正确的 Express Request 类型时遇到了一些问题。我有一个使用此代码传递的简单用户注册:
import { userRegister } from '../../controllers/user';
import { Request, Response, NextFunction } from 'express';
describe('User Registration', () => {
test('User has an invalid first name', async () => {
const mockRequest: any = {
body: {
firstName: 'J',
lastName: 'Doe',
email: 'jdoe@abc123.com',
password: 'Abcd1234',
passwordConfirm: 'Abcd1234',
company: 'ABC Inc.',
},
};
const mockResponse: any = {
json: jest.fn(),
status: jest.fn(),
};
const mockNext: NextFunction = jest.fn();
await userRegister(mockRequest, mockResponse, mockNext);
expect(mockNext).toHaveBeenCalledTimes(1);
expect(mockNext).toHaveBeenCalledWith(
new Error('First name must be between 2 and 50 characters')
);
});
});
但是,如果我改变:
const mockRequest: any = {
body: {
firstName: 'J',
lastName: 'Doe',
email: 'jdoe@abc123.com',
password: 'Abcd1234',
passwordConfirm: 'Abcd1234',
company: 'ABC Inc.',
},
};
到:
const mockRequest: Partial<Request> = {
body: {
firstName: 'J',
lastName: 'Doe',
email: 'jdoe@abc123.com',
password: 'Abcd1234',
passwordConfirm: 'Abcd1234',
company: 'ABC Inc.',
},
};
根据 TypeScript 文档 (https://www.typescriptlang.org/docs/handbook/utility-types.html#partialt),这应该使 Request 对象上的所有字段都是可选的。
但是,我收到此错误:
Argument of type 'Partial<Request>' is not assignable to parameter of type 'Request'.
Property '[Symbol.asyncIterator]' is missing in type 'Partial<Request>' but required in type 'Request'.ts(2345)
stream.d.ts(101, 13): '[Symbol.asyncIterator]' is declared here.
我希望有更多 TypeScript 经验的人可以发表评论并让我知道我做错了什么。
【问题讨论】:
-
您对
Partial<Request>所做的事情是正确的,但我敢打赌,问题在于userRegister不接受Partial<Request>- 它需要Request对吗?您可以将 mockRequest 声明为Request吗?const mockRequest: Partial<Request> ...如果没有,你可以给我们一个断言:await userRegister(mockRequest as Request, mockResponse, mockNext); -
现在看起来像这样:
export const userRegister = async ( req: express.Request, res: express.Response, next: express.NextFunction ) => {。模拟在测试中。我现在通过使用:const mockRequest: any = { body: { firstName: 'J', lastName: 'Doe', email: 'jdoe@abc123.com', password: 'Abcd1234', passwordConfirm: 'Abcd1234', company: 'ABC Inc.', }, };解决了这个问题。但我被告知尽量不要使用any,因为它违背了 TypeScript 的目的。 -
啊啊啊。我知道了。是的,
userRegister确实需要req: express.Request和res: express.Response。有趣,但对于测试,有没有办法解决这个问题?我想我在any工作时感到困惑。 -
你能把userRegister函数贴在这里,让我们看看这个函数的类型声明吗?
标签: typescript express jestjs