【发布时间】:2021-10-29 23:19:49
【问题描述】:
与Using partial shape for unit testing with typescript 非常相似,但我不明白为什么 Partial 类型被视为与完整版本不兼容。
我有一个单元测试,如果 AWS lambda 事件中的 body 无效,它会检查 lambda 是否返回 400。为了避免给我的同事制造噪音,我不想创建具有完整APIGatewayProxyEvent 的所有属性的invalidEvent。因此使用Partial<APIGatewayProxyEvent>。
it("should return 400 when request event is invalid", async () => {
const invalidEvent: Partial<APIGatewayProxyEvent> = {
body: JSON.stringify({ foo: "bar" }),
};
const { statusCode } = await handler(invalidEvent);
expect(statusCode).toBe(400);
});
const { statusCode } = await handler(invalidEvent); 行编译失败:
Argument of type 'Partial<APIGatewayProxyEvent>' is not assignable to parameter of type 'APIGatewayProxyEvent'.
Types of property 'body' are incompatible.
Type 'string | null | undefined' is not assignable to type 'string | null'.
Type 'undefined' is not assignable to type 'string | null'.ts(2345)
我知道APIGatewayProxyEvent 正文可以是string | null(通过查看类型)但string | null | undefined 来自哪里?为什么我的body(它是一个字符串)不是APIGatewayProxyEvent 的有效主体
如何使用 TypeScript Partials 测试 AWS Lambda?
我可以使用as to do type assertions,但我发现Partials 更明确。以下代码虽然有效:
const invalidEvent = { body: JSON.stringify({ foo: "bar" }) } as APIGatewayProxyEvent;
更新:使用 Omit 和 Pick 创建新类型
type TestingEventWithBody = Omit<Partial<APIGatewayProxyEvent>, "body"> & Pick<APIGatewayProxyEvent, "body">;
it("should return 400 when request event is invalid", async () => {
const invalidEvent: TestingEventWithBody = { body: JSON.stringify({ foo: "bar" }) };
const { statusCode } = await handler(invalidEvent);
expect(statusCode).toBe(400);
});
失败:
Argument of type 'TestingEventWithBody' is not assignable to parameter of type 'APIGatewayProxyEvent'.
Types of property 'headers' are incompatible.
Type 'APIGatewayProxyEventHeaders | undefined' is not assignable to type 'APIGatewayProxyEventHeaders'.
Type 'undefined' is not assignable to type 'APIGatewayProxyEventHeaders'.ts(2345)
【问题讨论】:
-
string | null | undefined来自于获取string | null并添加undefined,这就是Partial所做的,以使每个属性都是可选的。正文是一个字符串,但这无关紧要——它是通过一个可能不是的接口访问的。 -
@jonrsharpe 当然可以,但是为什么使用字符串作为键,而不允许使用字符串呢?
-
并且该错误不是来自分配给
invalidEvent,当您尝试将它传递给handler时它会出现,它需要APIGatewayProxyEvent而不是@ 987654346@(因为后者可能缺少handler需要的任何或所有属性)。 -
当您调用函数时,您不使用字符串 - 这就是问题所在。这正是错误消息告诉您的内容。您正在使用
Partial<APIGatewayProxyEvent>,其body是string | null | undefined。 “我无法理解为什么 Partial 类型被视为与完整版本不兼容” - 因为根据定义(假设您没有在所有道具已经是可选的东西上冗余使用它) 这就是Partial所做的,它使需要的属性不再需要。 -
是的,这将是接口隔离原则的应用,将
handler限制在它实际工作所需的属性上。APIGatewayProxyEvent与Partial<APIGatewayProxyEvent>或通过Pick或Omit具有子集或属性的东西兼容,反之则不然。
标签: typescript amazon-web-services jestjs partials ts-jest