用 Jest 模拟 new Function() [英] Mock new Function() with Jest

查看:16
本文介绍了用 Jest 模拟 new Function()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having trouble trying to mock a module with a constructor

// 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', () => {
  // ????
});

它不像文档示例 模拟模块,因为您需要导入后实例化模块.也不像模拟函数.

It's not like the Documentation example Mocking Modules because you need to instantiate the module after importing it. And isn't either like Mocking a Function.

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

How could I mock this doSomething() function while testing?

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

For reference, I'm trying to mock @google-cloud/* packages here. And I have a few projects that could take advantage on this.

推荐答案

您需要先模拟整个模块,以便返回一个笑话模拟.然后导入您的测试并将模拟设置为一个函数,该函数返回一个保存 doSomething 间谍的对象.对于测试,使用 new 调用的类和使用 new 调用的函数之间存在差异.

You need to mock the whole module first so that returns a jest mock. Then import into your test and set the mock to a function that returns an object holding the spy for doSomething. For the test there is difference between of a class called with new and a function called with new.

import ServiceLibrary from 'service-library'

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

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

这篇关于用 Jest 模拟 new Function()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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