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

标签 node.js unit-testing google-cloud-platform mocking jestjs

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

// 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/

相关文章:

java - "Test Artifact"选择器在Android STudio中做什么

c# - 当返回类型为 ActionResult 时,如何对操作进行单元测试?

javascript - 三元运算符中的三元运算符是否可能

node.js - 如何使用nodejs从excel表格中读取图像?

javascript - NodeJS 从 AWS S3 存储桶下载文件

ios - 从命令行运行 Xcode 单元测试时出错

kubernetes - 在 k8s 上提供视频/图像等静态内容的推荐方式

javascript - 在 Cloud Functions for Firebase 中启用 CORS

java - 在数据库操作上发布事件

javascript - 从 Node.js 中的 Buffer 解析 multipart/form-data