elastic / elasticsearch-js-mock

Mock utility for the Elasticsearch's Node.js client
https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/client-testing.html
Apache License 2.0
46 stars 10 forks source link

How to mock bulk method #19

Open kksarma opened 3 years ago

kksarma commented 3 years ago

Hi, I am trying to mock the bulk method but it is returning the following error:

import { Client } from '@elastic/elasticsearch';
import ElasticMock from '@elastic/elasticsearch-mock';

const esResponse = { took: 9, errors: false };

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

mock.add({
  method: 'POST',
  path: '/_bulk'
}, () => esResponse);

let response;
try {
  response = await client.bulk({ body: [{ foo: 'bar' }, { baz: 'fa\nz' }] });
  console.log(response);
} catch (error) {
  console.log(error);
  response = { body: {} };
}
ResponseError: Response Error
          at onBody (/Users/krishankant/Public/Work/fw-bt-3ds-metrics-lambda/node_modules/@elastic/elasticsearch/lib/Transport.js:349:23)
          at Class.onEnd (/Users/krishankant/Public/Work/fw-bt-3ds-metrics-lambda/node_modules/@elastic/elasticsearch/lib/Transport.js:275:11)
          at Class.emit (events.js:223:5)
          at endReadableNT (/Users/krishankant/Public/Work/fw-bt-3ds-metrics-lambda/node_modules/readable-stream/lib/_stream_readable.js:1010:12)
          at processTicksAndRejections (internal/process/task_queues.js:81:21) {
        name: 'ResponseError',
        meta: {
          body: { error: 'Mock not found' },
          statusCode: 404,
          headers: {
            'content-type': 'application/json;utf=8',
            date: '2021-08-16T12:09:51.899Z',
            connection: 'keep-alive',
            'content-length': 26
          },
          meta: {
            context: null,
            request: [Object],
            name: 'elasticsearch-js',
            connection: [Object],
            attempts: 0,
            aborted: false
          }
        }
      }

Can anyone help me to resolve this issue?

iamEAP commented 2 years ago

I ran into this and was able to find the underlying missing mock by digging deeper into the returned error. In the above example, logging error.meta.meta.request showed the mock (path, method) that needed to be implemented.

In my case, it ended up being a GET /:index/_refresh call, but I imagine, depending on the operation, the missing request mock could be different.