Skip to content

Instantly share code, notes, and snippets.

@humphd
Created February 2, 2022 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save humphd/4fecc0251ecb16fe160a1ec0035943f3 to your computer and use it in GitHub Desktop.
Save humphd/4fecc0251ecb16fe160a1ec0035943f3 to your computer and use it in GitHub Desktop.
Elastic mock brainstorm
const { Elastic } = require(...)
const { mock } = Elastic();
beforeEach(() => mock.clearAll())
test('..', async () => {
mock.add('.....');
await request.get('/serach?...')
})
/////////////////////////////////////////////////////////
const { ELASTIC_URL, ELASTIC_PORT } = process.env;
const { Client } = require('@elastic/elasticsearch');
const Mock = require('@elastic/elasticsearch-mock');
const logger = require('./logger');
let mock;
function MockClient(options) {
const client = new Client({
node: 'http://localhost:9200',
Connection: mock.getConnection(),
});
// Provide a fake health check
client.cluster.health = () => Promise.resolve();
return client;
}
// elasticUrl will either come from the ENV or will be defined locally
const elasticUrl = `${ELASTIC_URL}:${ELASTIC_PORT}`;
// Keep track of all clients we create, so we can close them on shutdown
const clients = [];
function createElasticClient(options = {}) {
// Use either a real Elastic Client or a Mock instance, depending on env setting
let client;
if (process.env.MOCK_ELASTIC) {
mock = mock || new Mock();
client = new Mock(options);
client.mock = mock;
} else {
client = new Elastic({...options, node: elasticUrl});
}
clients.push(client);
return client;
}
module.exports.Elastic = createElasticClient;
// Quit all connections gracefully
module.exports.shutDown = () =>
Promise.all(
clients.map(async (client) => {
try {
await client.close();
} catch (err) {
logger.debug({ err }, 'unable to close elasticsearch connection');
}
})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment