@elastic/elasticsearch-mock

中文文档
2.1.0发布于 2025/04/19Apache-2.0TypeScriptCommonJS近 30 天下载 22.4万

Mock utility for the Elasticsearch's Node.js client

原始使用文档
文档目录8 节
  1. Features
  2. Install
  3. Usage
  4. API
  5. Mock patterns
  6. Dynamic responses
  7. Errors
  8. License

Elasticsearch Node.js client mock utility

js-standard-style build

When testing your application you don't always need to have an Elasticsearch instance up and running, but you might still need to use the client for fetching some data. If you are facing this situation, this library is what you need.

Use v1.0.0 for @elastic/elasticsearch ≤ v7 compatibility and v2.0.0 for @elastic/elasticsearch ≥ v8 compatibility.

Features

  • Simple and intuitive API
  • Mocks only the http layer, leaving the rest of the client working as usual
  • Maximum flexibility thanks to "strict" or "loose" mocks

Install

npm install @elastic/elasticsearch-mock --save-dev

Usage

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: 'GET',
  path: '/_cat/health'
}, () => {
  return { status: 'ok' }
})

client.cat.health()
  .then(console.log)
  .catch(console.log)

API

Constructor

Before start using the library you need to create a new instance:

const Mock = require('@elastic/elasticsearch-mock')
const mock = new Mock()

add

Adds a new mock for a given pattern and assigns it to a resolver function.

// every GET request to the `/_cat/health` path
// will return `{ status: 'ok' }`
mock.add({
  method: 'GET',
  path: '/_cat/health'
}, () => {
  return { status: 'ok' }
})

You can also specify multiple methods and/or paths at the same time:

// This mock will catch every search request against any index
mock.add({
  method: ['GET', 'POST'],
  path: ['/_search', '/:index/_search']
}, () => {
  return { status: 'ok' }
})

get

Returns the matching resolver function for the given pattern, it returns null if there is not a matching pattern.

const fn = mock.get({
  method: 'GET',
  path: '/_cat/health'
})

clear

Clears/removes mocks for specific route(s).

mock.clear({
  method: ['GET'],
  path: ['/_search', '/:index/_search']
})

clearAll

Clears all mocks.

mock.clearAll()

getConnection

Returns a custom Connection class that you must pass to the Elasticsearch client instance.

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 patterns

A pattern is an object that describes an http query to Elasticsearch, and it looks like this:

interface MockPattern {
  method: string
  path: string
  querystring?: Record<string, string>
  body?: Record<string, any>
}

The more field you specify, the more the mock will be strict, for example:

mock.add({
  method: 'GET',
  path: '/_cat/health'
  querystring: { pretty: 'true' }
}, () => {
  return { status: 'ok' }
})

client.cat.health()
  .then(console.log)
  .catch(console.log) // 404 error

client.cat.health({ pretty: true })
  .then(console.log) // { status: 'ok' }
  .catch(console.log)

You can craft custom responses for different queries:

mock.add({
  method: 'POST',
  path: '/indexName/_search'
  body: { query: { match_all: {} } }
}, () => {
  return {
    hits: {
      total: { value: 1, relation: 'eq' },
      hits: [{ _source: { baz: 'faz' } }]
    }
  }
})

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

You can also specify dynamic urls:

mock.add({
  method: 'GET',
  path: '/:index/_count'
}, () => {
  return { count: 42 }
})

client.count({ index: 'foo' })
  .then(console.log) // => { count: 42 }
  .catch(console.log)

client.count({ index: 'bar' })
  .then(console.log) // => { count: 42 }
  .catch(console.log)

Wildcards are supported as well.

mock.add({
  method: 'HEAD',
  path: '*'
}, () => {
  return ''
})

client.indices.exists({ index: 'foo' })
  .then(console.log) // => true
  .catch(console.log)

client.ping()
  .then(console.log) // => true
  .catch(console.log)

Dynamic responses

The resolver function takes a single parameter which represent the API call that has been made by the client. You can use it to craft dynamic responses.

mock.add({
  method: 'POST',
  path: '/indexName/_search',
}, params => {
  return { query: params.body.query }
})

Errors

This utility uses the same error classes of the Elasticsearch client, if you want to return an error for a specific API call, you should use the ResponseError class:

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

const mock = new Mock()
mock.add({
  method: 'GET',
  path: '/_cat/health'
}, () => {
  return new errors.ResponseError({
    body: { errors: {}, status: 500 },
    statusCode: 500
  })
})

License

This software is licensed under the Apache 2 license.

版本与发布记录

@elastic/elasticsearch-mock 共发布 9 个版本,首次发布于 2020/04/10;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.1.0latest2025/04/191.6 年前
2.0.12024/10/242 年前
2.0.02022/03/114 年前
1.0.02022/01/124 年前
0.3.12021/08/305 年前
0.3.02020/07/226 年前

关于 @elastic/elasticsearch-mock 的常见问题

@elastic/elasticsearch-mock 是什么?

Mock utility for the Elasticsearch's Node.js client

如何安装 @elastic/elasticsearch-mock?

在项目目录运行 npm install @elastic/elasticsearch-mock,或使用 pnpm add / yarn add / bun add。

@elastic/elasticsearch-mock 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@elastic/elasticsearch-mock 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@elastic/elasticsearch-mock 可以商用吗?

@elastic/elasticsearch-mock 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@elastic/elasticsearch-mock 的下载量有多少?

根据 npm 官方下载统计,@elastic/elasticsearch-mock 在 2026/10/13 – 2026/11/11 这 30 天内被下载 224,339 次,日均约 7,478 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@elastic/elasticsearch-mock 还在维护吗?

最新版本 2.1.0 发布于 2025/04/19(1.6 年前);至今共发布 9 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/04/10。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。