typescript Jest expect.objectContaining失败,即使预期对象是接收对象的一部分

lf5gs5x2  于 2023-02-25  发布在  TypeScript
关注(0)|答案(1)|浏览(121)

我想用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"}}}}, {}
cld4siwp

cld4siwp1#

原因显然是middy在后台调用了接收两个参数await baseHandler(request.event, request.context);的基本处理程序
提示应该是测试运行器的接收输出末尾的{}
因此更新后的匹配器应该如下所示:

expect(mockHandler)
    .toHaveBeenCalledWith(expect.objectContaining({ 
     importantData:'important'} ), expect.anything());

这将引发一个Assert,因此您必须在测试开始时添加expect.assertions(1)
我不完全理解为什么会发生Assert,但我假设.toHaveBeenCalledWith会引发一个Assert,因为我们没有精确的匹配。

相关问题