用玩笑嘲笑新的Function() [英] Mock new Function() with Jest

查看:75
本文介绍了用玩笑嘲笑新的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}))

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

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