我想用jest测试我的middy中间件的lambda处理器,在中间件中我给request.event
分配了一个属性,然后在处理器中使用。
//hander.ts
const main = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
return {
statusCode: 200,
body: `some`
};
};
export const handler = middy(main)
.use(myCustomMiddware('somedata'));
// myCustomMiddleware.ts
export const myCustomMiddleware = (data: string): middy.MiddlewareObj<APIGatewayProxyEvent, APIGatewayProxyResult> => {
const before: middy.MiddlewareFn<APIGatewayProxyEvent, APIGatewayProxyResult> = async (request): Promise<void> => {
// Do stuff
Object.assign(request.event, { importantData: 'important' } as { importantData: string });
};
};
return {
before
};
现在我想写一个测试,看看处理程序是否接收到正确的值:
// in my .test.ts file
describe('test', () => {
const mockHandler = jest.fn(async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
return {
statusCode: 200,
body: ''
};
});
it('event should contain assigned value', () => {
const request = {
event: {
requestContext: {
authorizer: {
claims: {
'custom:SomeClaimA': 'claimA',
'custom:SomeClaimB': '1'
}
}
}
}
};
const middleware = middy(mockHandler).use(myCustomMiddleware('somedata'));
await middleware.before(request as never);
expect(mockHandler).toHaveBeenCalledWith(expect.objectContaining({ importantData:'important'} ));
});
但是由于某种原因,jest告诉我importantData
不是接收参数的一部分,而实际上它是接收参数的一部分。
Error: expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: ObjectContaining {"importantData": "important"}
Received: {"importantData": "important", "requestContext": {"authorizer": {"claims": {"custom:SomeClaimA": "SomeClaimA", "custom:SomeClaimB": "1"}}}}, {}
1条答案
按热度按时间cld4siwp1#
原因显然是middy在后台调用了接收两个参数
await baseHandler(request.event, request.context);
的基本处理程序提示应该是测试运行器的接收输出末尾的
{}
。因此更新后的匹配器应该如下所示:
这将引发一个Assert,因此您必须在测试开始时添加
expect.assertions(1)
。我不完全理解为什么会发生Assert,但我假设
.toHaveBeenCalledWith
会引发一个Assert,因为我们没有精确的匹配。