Originally published so you can compare all the changes. But now let’s go through it step by step.
1. Install additional modules
yarn add --dev jest @shelf/jest-elasticsearch @types/jest
2. Add jest-config.js
touch jest.config.js
module.exports = {
preset: '@shelf/jest-elasticsearch',
clearMocks: true,
collectCoverage: true,
coverageDirectory: "coverage",
coverageProvider: "v8"
};
Alternatively, you can generate jest config on your own using the
As an example let’s cover create function business logic.
const {ulid} = require('ulid');
const {client, index} = require("../elastic.js");
module.exports.createHandler = async (request, h) => {
if (Object.keys(request.payload))
try {
const res = await this.create(request.payload)
return h.response(res).code(200);
} catch (e) {
console.log({e})
return h.response({e}).code(400);
}
}
// let's cover this function with some tests
module.exports.create = async (entity) => {
const {
type,
value,
name,
} = entity;
const document = {
id: ulid(),
type: type.trim().toLowerCase(),
value: +value.toFixed(0),
name: name.trim()
}
await client.index({
index,
document
});
return document.id
}
Create a test file and add a couple of statements.
touch src/create/index.test.js
const {create} = require("./index.js");
const {client, index} = require("../elastic");
describe('#create', () => {
// clear elastic every time before running it the statement.
// It's really important since each test would be idempotent.
beforeEach(async () => {
await client.deleteByQuery({
index,
query: {
match_all: {}
}
})
await client.indices.refresh({index})
})
it('should insert data', async () => {
expect.assertions(3);
const res = await create({type: 'some', value: 100, name: 'jacket'})
await client.indices.refresh();
const data = await client.search({
index,
query: {
match: {
"id": res
}
}
})
expect(res).toEqual(expect.any(String))
expect(res).toHaveLength(26);
expect(data.hits.hits[0]._source).toEqual({
"id": res,
"name": "jacket",
"type": "some",
"value": 100
}
);
})
it('should insert and process the inserted fields', async () => {
const res = await create({type: 'UPPERCASE', value: 25.99, name: ' spaces '})
await client.indices.refresh();
const data = await client.search({
index,
query: {
match: {
"id": res
}
}
})
expect(data.hits.hits[0]._source).toEqual({
"id": res,
"name": "spaces",
"type": "uppercase",
"value": 26
}
);
})
});
A basic testing flow for each business logic function can be simply described like this:
insert data-> run tested function -> check outputs -> clear data -> repeat
Data insertion/deletion can be improved by unifying them into helpers and using additional mooching libs.
The elastic teardown is managed by
Resources
Now you know how to test your Elasticsearch queries using jest.
Hope this article will help you set up and test your elastic project!
Want to connect?
Follow me on
Optimizing massive MongoDB inserts, load 50 million records faster by 33%!
SOCIAL SHARE CARD GENERATOR