【问题标题】:How to test a mocked method that is used as a called function parameter -in a curry function- and not as a direct called function?如何测试用作被调用函数参数的模拟方法 - 在 curry 函数中 - 而不是作为直接调用函数?
【发布时间】:2020-08-19 13:13:20
【问题描述】:

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

基本上我想检查是否调用了 console.log 或 console.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
   })
  })
})

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

【问题讨论】:

    标签: javascript unit-testing logging mocking currying


    【解决方案1】:

    看起来模拟工作正常,因为如果您将调用 console.log 包装在像 debug: log((message: any) => console.log(message)) 这样的箭头函数中,则测试通过。

    【讨论】:

    • 啊我知道这种方式可以工作,但是我的代码不同,我有一个咖喱函数,方法console.log是通过参数logFn传递给函数的。所以问题仍然没有回答我。还是我错过了什么?要清楚。我希望这是真的logger.debug(text); expect(consoleSpy).toHaveBeenCalledTimes(1); expect(consoleSpy).toHaveBeenCalledWith(text)
    猜你喜欢
    • 2019-12-02
    • 2016-11-18
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多