使用 Jest 测试 AWS Severless 应用程序

问题描述 投票:0回答:1

我下面有一个基本的无服务器应用程序,我想使用 Jest 测试是否调用 getUserById 方法。我也在使用 inversifyjs。 现在,当我运行测试时,我收到错误TypeError: Reflect.hasOwnMetadata is not a function。 另一件事是我如何在这里模拟回复?

handler.spec.ts

import { IUsersHandler } from './../src/IUsersHandler';
import { UsersHandler } from './../src/UsersHandler';
import { APIGatewayProxyResult } from 'aws-lambda';

let handler: IUsersHandler;
let mockResponse: APIGatewayProxyResult;

describe('UsersHandler', () => {
  beforeEach(() => {
    handler = new UsersHandler();
  });

  it('should call getUserById method', () => {
    const spy = jest.spyOn(handler, 'getUserById').mockImplementation(async () => mockResponse);
    expect(spy).toBeCalledTimes(1);
  });
});

UsersHandler 类

import { IUsersHandler } from './IUsersHandler';
import { injectable } from 'inversify';
import { APIGatewayProxyHandler, APIGatewayProxyResult, APIGatewayProxyEvent } from 'aws-lambda';

@injectable()
export class UsersHandler implements IUsersHandler {
  constructor() {}
  public getUserById: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
    try {
      return {
        statusCode: 200,
        body: JSON.stringify(event),
      };
    } catch (err) {
      return {
        statusCode: 500,
        body: JSON.stringify(err),
      };
    }
  };
}

用户界面

import { APIGatewayProxyHandler } from 'aws-lambda';
export interface IUsersHandler {
  getUserById: APIGatewayProxyHandler;
}
export const TUsersHandler = Symbol.for('IUsersHandler');

Handler.ts

import { IUsersHandler, TUsersHandler } from './src/IUsersHandler';
import { container } from "./src/inversify.config";
import 'source-map-support/register';

export const getUserById = async function (event, context, callback) {
  const handler: IUsersHandler = container.get<IUsersHandler>(TUsersHandler);
    return handler.getUserById(event, context, callback);
  };
amazon-web-services serverless
1个回答
1
投票

最终 handler.spec.ts

import 'reflect-metadata';
import { IUsersHandler } from './../src/IUsersHandler';
import { UsersHandler } from './../src/UsersHandler';
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';

let handler: IUsersHandler;
let mockEvent: APIGatewayProxyEvent;
let mockResponse: APIGatewayProxyResult;

describe('UsersHandler', () => {
  beforeEach(() => {
    mockResponse = {
      statusCode: 200,
      body: 'This is a test',
    };
    handler = new UsersHandler();
  });

  it('should call getUserById method', async () => {
    const spy = jest.spyOn(handler, 'getUserById').mockImplementation(async () => mockResponse);
    const response: any = await handler.getUserById(mockEvent, null, null);
    expect(spy).toBeCalledTimes(1);
    expect(response.body).toBe('This is a test');
    expect(response.statusCode).toBe(200);
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.