首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jest:如何使用构造函数手动模拟模块(ioredis)

Jest:如何使用构造函数手动模拟模块(ioredis)
EN

Stack Overflow用户
提问于 2017-05-22 15:11:15
回答 2查看 7K关注 0票数 2

我正在遵循Jest 这里中的手动模拟示例

我试图将这个示例扩展到我自己的项目和ioredis (mocks/ioredis.js).的手动模拟我试图用自己的工具来模拟ioredis客户端hget (这样我就可以返回测试值),但是我遇到了问题,因为在访问模拟的let client = Redis.new之前,我需要用构造函数client.hget创建一个redis客户机。

下面是我对ioredis的手工模拟:

代码语言:javascript
复制
// __mocks__/ioredis.js
/* eslint-env node */
'use strict';

const IORedis = jest.genMockFromModule('ioredis');

const hget = jest.fn()
  .mockImplementationOnce(cb => cb(null, '123'))
  .mockImplementationOnce(cb => cb(null, '456'));

// this approach does not work, I'm wondering if I have to create the client
IORedis.hget = hget;  
module.exports = IORedis;

当我进行测试时,我可以看到ioredis确实受到了嘲弄,如果我在使用之前在实际模块中执行console.log(this.client.hget),我会看到以下内容:

代码语言:javascript
复制
{ [Function]
      _isMockFunction: true,
      getMockImplementation: [Function],
      mock: [Getter/Setter],
      mockClear: [Function],
      mockReset: [Function],
      mockReturnValueOnce: [Function],
      mockReturnValue: [Function],
      mockImplementationOnce: [Function],
      mockImplementation: [Function],
      mockReturnThis: [Function],
      mockRestore: [Function],
      _protoImpl:
       { [Function]
         _isMockFunction: true,
         getMockImplementation: [Function],
         mock: [Getter/Setter],
         mockClear: [Function],
         mockReset: [Function],
         mockReturnValueOnce: [Function],
         mockReturnValue: [Function],
         mockImplementationOnce: [Function],
         mockImplementation: [Function],
         mockReturnThis: [Function],
         mockRestore: [Function] } }

在我的实际测试中,没有返回任何内容,如果我删除手动模拟hget函数,我在控制台日志中也会看到同样的情况。我假设对于任何需要构造函数(而不是"fs“示例)的模块都会存在这个问题,所以答案可能是通用的。

EN

回答 2

Stack Overflow用户

发布于 2017-05-23 00:55:06

结果发现解决方案很简单。在我的ioredis手动模拟中,我只需要这样做:

//原答复

代码语言:javascript
复制
IORedis.prototype.hget = jest.genMockFn();
IORedis.prototype.hget.mockImplementation(function (key, link) {
    // return whatever I want here
});

module.exports = IORedis;

//最新版本的Jest

代码语言:javascript
复制
const IORedis = jest.genMockFromModule("ioredis");
IORedis.prototype.hget = jest.fn((key, link) => {
        // return whatever I want here
    });



module.exports = IORedis;
票数 5
EN

Stack Overflow用户

发布于 2020-05-19 22:19:51

如果你正在使用西农作为你的顽固库。你可以给它做存根。

代码语言:javascript
复制
import { createSandbox } from 'sinon';  
import * as ioredis from 'ioredis';

beforeAll(() => {
  const sandbox = createSandbox();

  sandbox.stub(ioredis.prototype, 'connect').returns(Promise.resolve());
  sandbox.stub(ioredis.prototype, 'sendCommand').returns(Promise.resolve());
})

afterAll(() => {
  sandbox.restore();
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44116458

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档