嘲笑静态吸气剂

时间:2020-06-02 14:57:19

标签: node.js typescript jestjs

我正在尝试模拟具有静态获取器的日志记录服务。

  static get error(): Function {
    return console.error.bind(console, 'Error: ');
  }

尝试过: jest.spyOn(ConsoleLoggingService, 'error').mockImplementation(() => 'blah');

但是我得到TypeError: Cannot set property info of function ConsoleLoggingService() {} which has only a getter

也尝试过: jest.spyOn(ConsoleLoggingService, 'error', 'get').mockImplementation(() => 'blah'); 并获得TypeError: console_logging_service_1.ConsoleLoggingService.error is not a function

有什么建议吗?

谢谢

1 个答案:

答案 0 :(得分:1)

jest.spyOn(ConsoleLoggingService, 'error', 'get').mockImplementation(() => ...)模拟get访问函数,因此,在返回字符串的同时,期望实现返回另一个函数。

它可以返回另一个间谍进行测试:

jest.spyOn(ConsoleLoggingService, 'error', 'get').mockReturnValue(jest.fn())
...
expect(ConsoleLoggingService.error).toBeCalledWith(...)

使用get的效率较低,因为该函数绑定在每个error的访问上。可以简化为:

static error = console.error.bind(console, 'Error: ')

嘲笑为:

jest.spyOn(ConsoleLoggingService, 'error').mockImplementation(() => {})
相关问题