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