如何测试在咖喱函数中用作被调用函数参数而不是直接被调用函数的模拟方法?

问题描述

这是要测试的代码,它是一个小的记录器模块,构建为一个组合对象,该对象具有由curry函数表示的键。这些curry函数的第一个参数是实际实现要调用方法方法(需要测试)。

基本上,我想检查是否调用console.logconsole.info

logger.ts

const log = (logFn: () => void) => (message: any) => {
  logFn(message)
}

const logger = {
  debug: log(console.log),info: log(console.info)
}

export default logger

logger.spec.ts

import logger from './logger'

describe('logger',() => {
  describe('debug',() => {
    it('sets a text as log output',() => {
      const consoleSpy = jest.spyOn(console,'log')
      const text = 'Export is working properly'

      logger.debug(text)

      expect(consoleSpy).toHaveBeenCalledTimes(1) // failure
      expect(consoleSpy).toHaveBeenCalledWith(text) // failure


      console.log(text)

      expect(consoleSpy).toHaveBeenCalledTimes(1) // success
      expect(consoleSpy).toHaveBeenCalledWith(text) // success
   })
  })
})

但是发生的是,如果我直接在我的console.log调用logger.ts,则测试会检测到该方法已被调用,而如果我调用了我的模块方法logFn通过咖喱函数间接console.log进行测试,则测试未检测到它。我想嘲笑的程度没有达到适当的范围。无论如何,问题是,有没有办法进行管理?谢谢

解决方法

看起来模拟程序正常工作,因为如果将调用console.log包装在箭头功能中,例如debug: log((message: any) => console.log(message)),则测试通过。