gpt4 book ai didi

node.js - 用 Jest 模拟 new Function()

转载 作者:搜寻专家 更新时间:2023-11-01 00:27:45 24 4
gpt4 key购买 nike

我在尝试使用构造函数模拟模块时遇到问题

// code.js
const ServiceClass = require('service-library');
const serviceInstance = new ServiceClass('some param');
exports.myFunction = () => {
serviceInstance.doSomething();
};

和测试代码:

// code.test.js
const ServiceClass = require('service-library');
jest.mock('service-library');
const {myFunction} = require('../path/to/my/code');

test('check that the service does something', () => {
// ????
});

这不像文档示例 Mocking Modules因为您需要在导入模块后对其进行实例化。并且既不像模拟函数。

我如何在测试时模拟这个 doSomething() 函数?

作为引用,我在这里尝试模拟 @google-cloud/* 包。我有几个项目可以利用这一点。

最佳答案

您需要先模拟整个模块,以便返回一个 Jest 模拟。然后导入到您的测试中并将模拟设置为一个函数,该函数返回一个包含 doSomething spy 的对象。对于测试,使用 new 调用的类和使用 new 调用的函数之间存在差异。

import ServiceLibrary from 'service-library'

jest.mock( 'service-library', () => jest.fn())

const doSomething = jest.fn()
ServiceLibrary.mockImplementation(() => ({doSomething}))

关于node.js - 用 Jest 模拟 new Function(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52859389/

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