Very similar to Using partial shape for unit testing with typescript but I'm failing to understand why the Partial type is seen as being incompatible with the full version.
I have a unit test which check if a lambda returns 400 if the body
in an AWS lambda event isn't valid. To avoid creating noise for my colleagues, I don't want to create invalidEvent
with all the properties of a full APIGatewayProxyEvent
. Hence using a 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);
});
The const { statusCode } = await handler(invalidEvent);
line fails compilation with:
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)
I understand APIGatewayProxyEvent
body can be string | null
(from looking at the types) but where did string | null | undefined
come from? Why isn't my body
- which is a string - a valid body for APIGatewayProxyEvent
How can I use TypeScript Partials to test AWS Lambda?
I could use as
to do type assertions but I find Partials more explicit. The following code works though:
const invalidEvent = { body: JSON.stringify({ foo: "bar" }) } as APIGatewayProxyEvent;
Update: using Omit and Pick to make a new type
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);
});
Fails with:
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)