# @elastic/elasticsearch-mock 中文文档

规范地址：https://npmcn.com/package/%40elastic/elasticsearch-mock/

版本：2\.1\.0
npm 元数据更新时间：2026-09-25T13:38:20.739Z
中文译文更新时间：2026-11-13T10:36:15.842Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40elastic/elasticsearch-mock
原文对照：https://npmcn.com/package/%40elastic/elasticsearch-mock/?lang=original
项目主页：https://github.com/elastic/elasticsearch-js-mock#readme
源码仓库：https://github.com/elastic/elasticsearch-js-mock

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：56 kB，11 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：3 个
- 首次发布：2020-04-10T10:19:13.184Z
- 最新版本发布：2025-04-18T18:53:33.801Z
- 近 30 天下载量：224339（2026-10-13 至 2026-11-11，npm 官方下载统计）
- 已发布版本数：9（近 12 个月 0 个）

## 中文简介

Elasticsearch 的节点客户端的模拟工具

## 安装

```sh
npm install @elastic/elasticsearch-mock
```

也可以使用：`pnpm add @elastic/elasticsearch-mock`、`yarn add @elastic/elasticsearch-mock`、`bun add @elastic/elasticsearch-mock`

## README

![](https://www.elastic.co/static-res/images/elastic-logo-200.png)

# 弹性搜索节点.js 客户端模拟工具

[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/) ![build](https://github.com/elastic/elasticsearch-js-mock/workflows/build/badge.svg)

在测试你的应用时 你并不总是需要 一个弹性搜索实例 并运行, 但您可能需要使用客户端获取一些数据. 如果你面临这种情况,这个图书馆就是你需要的.

使用 `v1.0.0` 页:1 `@elastic/elasticsearch` v7 兼容性和 `v2.0.0` 页:1 `@elastic/elasticsearch` v8 兼容性.

### 特征

-   简单而直观的 API
-   只嘲笑 http 层, 剩下的客户端照常工作
-   多亏了"收缩"或"放荡"的嘲弄

## 安装

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

## 使用量

```js
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`

在开始使用库之前, 您需要创建新实例 :

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

#### `add`

添加给定模式的新模拟并指定给解析器函数.

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

也可以同时指定多种方法和/或路径:

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

#### `get`

返回给定模式的匹配解析器函数, 它返回 `null` 如果不存在匹配模式.

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

#### `clear`

清除/删除对特定路线的模拟.

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

#### `clearAll`

清除所有嘲笑.

```js
mock.clearAll()
```

#### `getConnection`

返回自定义 `Connection` 上课你 **必须** 传递到 Elasticsearch 客户端实例 .

```js
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()
})
```

### 模拟图案

一个图案是描述 http 查询到 Elasticsearch 的对象, 它看起来像:

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

字段越多,模拟会越严格,例如:

```js
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)
```

您可以为不同的查询自定义回复 :

```js
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: []
    }
  }
})
```

您也可以指定动态 urls :

```js
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)
```

圆通也相助.

```js
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)
```

### 动态反应

解析器函数取一个代表客户端已调用的API的单一参数. 你可以用它来设计动态响应.

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

### 错误

此工具使用 Elasticsearch 客户端相同的错误类, 如果您想要返回特定 API 调用错误, 请使用 `ResponseError` 类 :

```js
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
  })
})
```

## 许可证

该软件根据 [Apache 2 许可证](https://npmcn.com/package/%40elastic/elasticsearch-mock/LICENSE)。 。 。 .

## 常见问题

### @elastic/elasticsearch-mock 是什么？

Elasticsearch 的节点客户端的模拟工具

### 如何安装 @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 和提交记录判断。

