用 Jest 模拟 new Function()

din*_*igo 7 unit-testing mocking node.js google-cloud-platform jestjs

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

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

和测试代码:

// 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', () => {
  // ????
});
Run Code Online (Sandbox Code Playgroud)

它不像文档示例模拟模块,因为您需要在导入后实例化模块。也不像 Mocking a Function。

我怎么能doSomething()在测试时模拟这个功能?

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

And*_*rle 9

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

import ServiceLibrary from 'service-library'

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

const doSomething = jest.fn()
ServiceLibrary.mockImplementation(() => ({doSomething}))
Run Code Online (Sandbox Code Playgroud)


din*_*igo 5

按照@andreas-köberle解决方案,我可以@google-cloud/bigquery像这样模拟:

// mock bigquery library
const BigQuery = require('@google-cloud/bigquery');
jest.mock('@google-cloud/bigquery', () => jest.fn());
const load = jest.fn(() => ({'@type': 'bigquery#load_job'}));
const table = jest.fn(() => ({load}));
const dataset = jest.fn(() => ({table}));
BigQuery.mockImplementation(() => ({dataset}));

// mock cloud storage library
const {Storage} = require('@google-cloud/storage');
jest.mock('@google-cloud/storage');
const file = jest.fn(name => ({'@type': 'storage#file', name}));
const bucket = jest.fn(() => ({file}));
Storage.mockImplementation(() => ({bucket}));
Run Code Online (Sandbox Code Playgroud)

我把这个留在这里作为参考,以防其他人用谷歌搜索类似的东西。但要说清楚,这只是@andreas-köberle 答案的一个特殊化