gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:55:26 25 4
gpt4 key购买 nike

我正在遵循 Jest 文档 here 中的手动模拟示例

我正在尝试将此示例扩展到我自己的项目和 ioredis 的手动模拟 (mocks/ioredis.js)。我正在尝试用我自己的 ioredis 客户端 hget 来模拟(这样我就可以返回测试值),但由于我需要使用构造函数 let 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 确实被 mock ,如果我在使用之前在实际模块中执行 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”示例相反),因此答案可能是通用的。

最佳答案

事实证明解决方案非常简单。在我的 ioredis 手动模拟中,我只需要这样做:

//原答案

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

module.exports = IORedis;

//Jest 的最新版本

const IORedis = jest.genMockFromModule("ioredis");
IORedis.prototype.hget = jest.fn((key, link) => {
// return whatever I want here
});



module.exports = IORedis;

关于jestjs - 如何使用构造函数手动模拟模块(ioredis),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44116458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com