如何使用 jest 模拟 node-redis

how to mock node-redis using jest

我正在使用 jest and trying to mock node-redis using redis-mock

// redis.js

const redis = require("redis");
const client = redis.createClient({ host: '127.0.0.1', port: 6379 });

// redis.test.js

const redisMock = require("redis-mock");

describe("redis", () => {
  jest.doMock("redis", () => jest.fn(() => redisMock));
  const redis = require("./redis");
});

当我 运行 测试时,我得到一个错误

TypeError: redis.createClient is not a function

我觉得我在使用 jest.doMock() 时做错了什么。

感谢您的帮助。

以下对我有用:

import redis from 'redis-mock'
jest.mock('redis', () => redis)

我根本没有在测试中包含 redis 库,但我只将它包含在包含测试 class 的文件中。 (测试过的class的文件当然包含在测试文件中了。)

如果您正在使用 jest, the switching of the mock and the actual implementation is possible automatically。非常适合 CI。

jest.config.js

module.exports = {
    // other properties...
    setupFilesAfterEnv: ['./jest.setup.redis-mock.js'],
};

jest.setup.redis-mock.js

jest.mock('redis', () => jest.requireActual('redis-mock'));