【发布时间】: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