Unit testing aws lambda handler that queries data from mock elasticsearch index

Viewed 56

I am trying to test an AWS lambda function that queries and returns data from elasticsearch.

I was able to find some documentation on how to create a mock elasticsearch and add data to the mock index via the below code.

const { Client } = require('@elastic/elasticsearch')
const Mock = require('@elastic/elasticsearch-mock')

const mock = new Mock()
const client = new Client({
  node: 'http://localhost:9200',
  Connection: mock.getConnection()
})

mock.add({
  method: 'POST',
  path: '/indexName/_search',
  body: { query: { match: { foo: 'bar' } } }
}, () => {
  return {
    hits: {
      total: { value: 0, relation: 'eq' },
      hits: []
    }
  }
})

My question how would I unit test an endpoint which queries the mock data? I have not been able to find much documentation on how to do this.

i.e. How do I modify the below unit test to use the mock elastic index created above instead of actually having to query a real elasticsearch index using docker or something equivalent which I am currently doing?

const mock = (
  partial: Partial<APIGatewayProxyEvent>
): APIGatewayProxyEvent => partial as APIGatewayProxyEvent;
const mockContext = {} as Context;
const mockCallback: Callback<APIGatewayProxyResult> = () => {
  return;

describe('lambda handler', () => {



  it('returns response', async () => {
    const result = await handler(
      mockEvent({ queryStringParameters: { name: 'dave' } }),
      mockContext,
      mockCallback
    );
    if (!result) {
      fail('no result');
    } else {
      expect(result.statusCode).toEqual(200);
      expect(JSON.parse(result.body)).toEqual(mockResponse);
    }
  });
});
};
0 Answers
Related