【问题标题】:Mock static getter with jest用笑话模拟静态吸气剂
【发布时间】:2020-09-21 02:14:39
【问题描述】:

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

  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

有什么建议吗?

谢谢

【问题讨论】:

  • 为什么它需要是访问器? ConsoleLoggingService.error可以直接做函数吗?
  • @PedroMutter 是的,我认为这过于复杂,但我试图避免修改代码(正在运行)来执行单元测试。
  • 我明白了...您可以尝试模拟整个文件 jest.mock('path/to/ConsoleLoggingService') 。然后他们导入它并在beforeAll 钩子中更改error 的值。喜欢ConsoleLoggingService.error = jest.fn()
  • 不工作。我收到一个 TS 错误 Cannot assign to 'error' because it is a read-only property

标签: node.js typescript jestjs


【解决方案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(() => {})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-07
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    相关资源
    最近更新 更多