npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@elastic/elasticsearch-mock

v2.0.1

Published

Mock utility for the Elasticsearch's Node.js client

Downloads

137,994

Readme

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.