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
47 stars 13 forks source link

How to seperate mocks from implementation? #32

Open mrbrianevans opened 9 months ago

mrbrianevans commented 9 months ago

I'm trying to use this mock to write unit tests for production code that makes calls to elasticsearch.

I am struggling to see how the actual production code can be seperated from the mock.

For example, how could a test be written for code like this:

async function executeQuery(){
  const client = new Client({
    auth: {
      api_key: ...
    },
  });
  await client.query(...)
}

Test using jest:

test('call execute query with mocked elasticsearch client', async ()=>{
  // what needs to go here to make the function use a mocked client?
  await executeQuery()
})

Having to pass the mock to the Connection parameter of creating the Client requires having the mock in the implementation code that I'm trying to test. Surely it must be possible to have seperate files for the implementation logic and the unit test?

The example shown in the docs shows creating the client and mocking the responses in the same file, but in a real project wouldn't these necessarily be in different places?