我在尝试使用构造函数模拟模块时遇到问题
// 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/