ioredis-mock vs redis-mock
Redis Mocking Libraries Comparison
1 Year
ioredis-mockredis-mock
What's Redis Mocking Libraries?

Redis mocking libraries are essential tools for developers who want to test applications that interact with Redis without requiring a live Redis server. They simulate the behavior of Redis, allowing for faster and more isolated tests. By using these libraries, developers can ensure that their code behaves correctly under various conditions without the overhead of a real database connection. This is particularly useful in unit tests and integration tests, where controlling the environment is crucial for reliable results.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
ioredis-mock698,6553606.98 MB882 years agoMIT
redis-mock152,078216-555 years agoMIT
Feature Comparison: ioredis-mock vs redis-mock

API Compatibility

  • ioredis-mock:

    ioredis-mock is designed to closely mimic the ioredis API, ensuring that tests using this mock behave similarly to those using a real Redis instance. This compatibility allows developers to write tests that are more representative of actual application behavior, reducing the risk of discrepancies between testing and production environments.

  • redis-mock:

    redis-mock provides a simpler API that mimics the native Redis client. While it may not cover all advanced features of Redis, it is sufficient for basic operations and is easy to integrate into existing projects that utilize the native Redis client.

Performance

  • ioredis-mock:

    ioredis-mock is optimized for performance, allowing for fast execution of tests without the need for a live Redis server. It can handle a large number of commands efficiently, making it suitable for applications with high throughput requirements during testing.

  • redis-mock:

    redis-mock is lightweight and performs well for simple use cases. However, it may not be as performant as ioredis-mock for complex scenarios or high-volume command execution, as it is designed to be a straightforward mock rather than a full-featured solution.

Feature Set

  • ioredis-mock:

    ioredis-mock supports a wide range of Redis commands and features, including pub/sub, transactions, and clustering. This makes it a robust choice for applications that rely on these advanced Redis functionalities, allowing for comprehensive testing scenarios.

  • redis-mock:

    redis-mock focuses on basic Redis commands and may lack support for some advanced features. It is ideal for projects that do not require extensive Redis functionality and need a quick and easy mocking solution.

Ease of Use

  • ioredis-mock:

    ioredis-mock is user-friendly and integrates seamlessly with existing ioredis-based applications. Its API is intuitive for developers familiar with ioredis, making it easy to set up and start writing tests quickly.

  • redis-mock:

    redis-mock is very straightforward to use, with minimal setup required. It is particularly suitable for developers who want to quickly mock Redis without delving into complex configurations.

Community and Support

  • ioredis-mock:

    ioredis-mock has a growing community and is actively maintained, providing users with regular updates and support. This can be beneficial for developers looking for long-term solutions and community-driven enhancements.

  • redis-mock:

    redis-mock has a smaller community and may not receive as frequent updates as ioredis-mock. However, it is still a reliable choice for simple mocking needs and has sufficient documentation for basic usage.

How to Choose: ioredis-mock vs redis-mock
  • ioredis-mock:

    Choose ioredis-mock if you are using the ioredis client in your application. It provides a comprehensive mocking solution that closely follows the ioredis API, making it easier to test your code without significant changes. It supports promises and callbacks, allowing for flexible testing scenarios.

  • redis-mock:

    Choose redis-mock if you are looking for a lightweight and simple mocking solution that works with the native Redis client. It is easy to set up and use, making it suitable for smaller projects or when you need a quick mock without the overhead of additional features.

README for ioredis-mock

ioredis-mock · npm npm version Redis Compatibility: 66% semantic-release

This library emulates ioredis by performing all operations in-memory. The best way to do integration testing against redis and ioredis is on a real redis-server instance. However, there are cases where mocking the redis-server is a better option.

Cases like:

  • Your workflow already use a local redis-server instance for the dev server.
  • You're on a platform without an official redis release, that's even worse than using an emulator.
  • You're running tests on a CI, setting it up is complicated. If you combine it with CI that also run selenium acceptance testing it's even more complicated, as two redis-server instances on the same CI build is hard.
  • The GitHub repo have bots that run the testing suite and is limited through npm package.json install scripts and can't fire up servers. (Having Renovatebot notifying you when a new release of ioredis is out and wether your code breaks or not is awesome).

Check the compatibility table for supported redis commands.

Usage (try it in your browser with RunKit)

const Redis = require('ioredis-mock')
const redis = new Redis({
  // `options.data` does not exist in `ioredis`, only `ioredis-mock`
  data: {
    user_next: '3',
    emails: {
      'clark@daily.planet': '1',
      'bruce@wayne.enterprises': '2',
    },
    'user:1': { id: '1', username: 'superman', email: 'clark@daily.planet' },
    'user:2': { id: '2', username: 'batman', email: 'bruce@wayne.enterprises' },
  },
})
// Basically use it just like ioredis

Browser usage (Experimental)

There's a browser build available. You can import it directly (import Redis from 'ioredis-mock/browser.js'), or use it on unpkg.com:

import Redis from 'https://unpkg.com/ioredis-mock'

const redis = new Redis()
redis.set('foo', 'bar')
console.log(await redis.get('foo'))

Breaking Changes

from v7 to v8

ioredis@v4 support dropped

ioredis@v5 is the new baseline. Stay on ioredis-mock@v7 until you're ready to upgrade to ioredis@v5.

PromiseContainer has been removed.

Support for third-party Promise libraries is dropped. The native Promise library will always be used.

from v6 to v7

createConnectedClient is removed

Replace it with .duplicate() or use another new Redis instance.

Dropped support for Node v10

It's been EOL since Apr, 2021 and it's recommended to upgrade to v14.x LTS.

ioredis-mock/jest.js is removed

ioredis-mock is no longer doing a import { Command } from 'ioredis' internally, it's now doing a direct import import Command from 'ioredis/built/command' and thus the jest.js workaround is no longer needed:

-jest.mock('ioredis', () => require('ioredis-mock/jest'))
+jest.mock('ioredis', () => require('ioredis-mock'))

from v5 to v6

Before v6, each instance of ioredis-mock lived in isolation:

const Redis = require('ioredis-mock')
const redis1 = new Redis()
const redis2 = new Redis()

await redis1.set('foo', 'bar')
console.log(await redis1.get('foo'), await redis2.get('foo')) // 'bar', null

In v6 the internals were rewritten to behave more like real life redis, if the host and port is the same, the context is now shared:

const Redis = require('ioredis-mock')
const redis1 = new Redis()
const redis2 = new Redis()
const redis3 = new Redis(6380) // 6379 is the default port

await redis1.set('foo', 'bar')
console.log(
  await redis1.get('foo'), // 'bar'
  await redis2.get('foo'), // 'bar'
  await redis3.get('foo') // null
)

And since ioredis-mock now persist data between instances, you'll likely need to run flushall between testing suites:

const Redis = require('ioredis-mock')

afterEach(done => {
  new Redis().flushall().then(() => done())
})

Pub/Sub channels

We also support redis publish/subscribe channels. Like ioredis, you need two clients:

const Redis = require('ioredis-mock')
const redisPub = new Redis()
const redisSub = new Redis()

redisSub.on('message', (channel, message) => {
  console.log(`Received ${message} from ${channel}`)
})
redisSub.subscribe('emails')
redisPub.publish('emails', 'clark@daily.planet')

Lua scripting

You can use the defineCommand to define custom commands using lua or eval to directly execute lua code.

In order to create custom commands, using lua scripting, ioredis exposes the defineCommand method.

You could define a custom command multiply which accepts one key and one argument. A redis key, where you can get the multiplicand, and an argument which will be the multiplicator:

const Redis = require('ioredis-mock')
const redis = new Redis({ data: { k1: 5 } })
const commandDefinition = {
  numberOfKeys: 1,
  lua: 'return redis.call("GET", KEYS[1]) * ARGV[1]',
}
redis.defineCommand('multiply', commandDefinition) // defineCommand(name, definition)
// now we can call our brand new multiply command as an ordinary command
redis.multiply('k1', 10).then(result => {
  expect(result).toBe(5 * 10)
})

You can also achieve the same effect by using the eval command:

const Redis = require('ioredis-mock')
const redis = new Redis({ data: { k1: 5 } })
const result = redis.eval(`return redis.call("GET", "k1") * 10`)
expect(result).toBe(5 * 10)

note we are calling the ordinary redis GET command by using the global redis object's call method.

As a difference from ioredis we currently don't support:

  • dynamic key number by passing the number of keys as the first argument of the command.
  • automatic definition of the custom command buffer companion (i.e. for the custom command multiply the multiplyBuffer which returns values using Buffer.from(...))
  • the evalsha command
  • the script command

Cluster(Experimental)

Work on Cluster support has started, the current implementation is minimal and PRs welcome #359

const Redis = require('ioredis-mock')

const cluster = new Redis.Cluster(['redis://localhost:7001'])
const nodes = cluster.nodes()
expect(nodes.length).toEqual(1)

Roadmap

You can check the roadmap project page, and the compat table, to see how close we are to feature parity with ioredis.

I need a feature not listed here

Just create an issue and tell us all about it or submit a PR with it! 😄