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

时间:2017-05-22 15:11:16

标签: jestjs

我按照Jest docs here

中的手动模拟示例进行操作

我试图将此示例扩展到我自己的项目和ioredis的手动模拟( mocks /ioredis.js)。我试图用我自己的模拟ioredis客户端hget(所以我可以返回测试值),但由于我需要用构造函数创建一个redis客户端,所以我遇到了麻烦(让client = Redis.new)之前我可以访问模拟的client.hget。

这是我对ioredis的手动模拟:

// __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),我会看到:

{ [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'示例)所以答案可能是通用的。

2 个答案:

答案 0 :(得分:2)

原来解决方案非常简单。在我的ioredis手册模拟中,我只需要这样做:

IORedis.prototype.hget = jest.genMockFn();
IORedis.prototype.hget.mockImplementation(function (key, link) {
    // return whatever I want here
});

module.exports = IORedis;

答案 1 :(得分:-1)

如果使用sinon作为存根库。您可以对ioredis存根。

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();
});