用笑话模拟静态 getter

lma*_*ves 4 node.js typescript jestjs

我正在尝试模拟具有静态吸气剂的日志记录服务。

  static get error(): Function {
    return console.error.bind(console, 'Error: ');
  }
Run Code Online (Sandbox Code Playgroud)

尝试过: 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

有什么建议么?

谢谢

Est*_*ask 6

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

它可以返回另一个间谍用于测试目的:

jest.spyOn(ConsoleLoggingService, 'error', 'get').mockReturnValue(jest.fn())
...
expect(ConsoleLoggingService.error).toBeCalledWith(...)
Run Code Online (Sandbox Code Playgroud)

使用 的get效率较低,因为该函数在每次error访问时都会绑定。它可以简化为:

static error = console.error.bind(console, 'Error: ')
Run Code Online (Sandbox Code Playgroud)

并嘲笑为:

jest.spyOn(ConsoleLoggingService, 'error').mockImplementation(() => {})
Run Code Online (Sandbox Code Playgroud)