javascript - Jest : How to mock one specific function when using module. 导出

标签 javascript node.js jestjs

我试图在使用 module.exports 时模拟一个特定的函数。我如何测试内部函数 B?

在我的 worker.js 中

module.exports = function () {
  this.funcA = funcA
  this.funcB = funcB
}

funcA () {
  funcB()
}

funcB() {...}

在我的 worker-test.js 中

const Worker = require('./worker')

test('test functionB', () => {...}) 

test('test functionA', () => {
  const work = new Worker()
  work.funcB = jest.fn()  //mock funcB
  work.funcA  //run funcA

  expect(work.funcB).toHaveBeenCalledTimes(1) //Error
}) 

我是 Jest 新手。在这种情况下有什么好的方法来模拟函数吗?

最佳答案

由于 funcA 直接调用 funcB,因此无法按照当前编写代码的方式模拟 funcB

修复它的最简单方法是注意 worker.js 返回一个构造函数,funcAfuncB 几乎 prototype methods ...

...如果您使它们成为原型(prototype)方法,则可以模拟 funcB:

worker.js

class Worker {
  funcA() {
    this.funcB();
  }
  funcB() {
    throw new Error('should not make it here');
  }
}

module.exports = Worker;

worker.test.js

const Worker = require('./worker');

test('test functionB', () => { /* ... */ })

test('test functionA', () => {
  const spy = jest.spyOn(Worker.prototype, 'funcB');  // <= spy on funcB
  spy.mockImplementation(() => {});  // <= mock funcB

  const work = new Worker();
  work.funcA();  // <= call funcA

  expect(spy).toHaveBeenCalledTimes(1);  // Success!
  spy.mockRestore();  // <= restore funcB
}) 

关于javascript - Jest : How to mock one specific function when using module. 导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55821609/

相关文章:

javascript - 使用 JAVAScript 从 Phonegap 应用程序向 DJANGO 提交表单

javascript - 为什么我的点击功能没有按预期工作?

javascript - react-testing-library:调试输出的某些部分不可见

javascript - Vuejs jquery datatable 直接插件无法正常工作

javascript - 在没有 Internet 连接时使用 jQuery

node.js - 使用 Node.JS zlib 模块解压缩没有 header 的 gzip 数据

node.js - 警告 : NODE_ENV value of 'test ' did not match any deployment config file names

javascript - Azure Function + Javascript如何获取我在post请求中传递的数据?

javascript - 当使用 `jest.useFakeTimers()` 时,为什么 `setImmediate` 不会无限期超时?

javascript - Jest 模拟 localStorage 方法