如何使用玩笑来模拟node-redis [英] how to mock node-redis using jest

查看:57
本文介绍了如何使用玩笑来模拟node-redis的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jest 并尝试模拟 redis -模拟.

i am using 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不是函数

TypeError: redis.createClient is not a function

让我感到在使用jest.doMock()时我做错了事.

feels to me that i am doing something wrong when using jest.doMock().

非常感谢您的协助.

推荐答案

以下对我有用:

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

我完全没有在测试中包含redis库,但是我仅将其包含在包含被测试类的文件中. (具有测试类的文件当然包含在测试文件中.)

I do not include the redis library in the test at all, but I include it only in the file which contains the tested class. (The file with tested class is, of course, included in the test file.)

这篇关于如何使用玩笑来模拟node-redis的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆