Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 开玩笑地模仿静态getter_Node.js_Typescript_Jestjs - Fatal编程技术网

Node.js 开玩笑地模仿静态getter

Node.js 开玩笑地模仿静态getter,node.js,typescript,jestjs,Node.js,Typescript,Jestjs,我试图模拟一个具有静态getter的日志服务 static get error(): Function { return console.error.bind(console, 'Error: '); } 试用: jest.spyOn(ConsoleLoggingService,'error').mockImplementation(()=>'blah') 但是我得到了TypeError:无法设置函数ConsoleLoggingService(){}的属性信息,该函数只有一个g

我试图模拟一个具有静态getter的日志服务

  static get error(): Function {
    return console.error.bind(console, 'Error: ');
  }
试用:
jest.spyOn(ConsoleLoggingService,'error').mockImplementation(()=>'blah')

但是我得到了
TypeError:无法设置函数ConsoleLoggingService(){}的属性信息,该函数只有一个getter

还尝试:
jest.spyOn(ConsoleLoggingService,'error','get').mockImplementation(()=>'blah')
获取
TypeError:console\u logging\u service\u 1.ConsoleLoggingService.error不是一个函数

有什么建议吗

感谢jest.spyOn(ConsoleLoggingService,'error','get')。mockImplementation(()=>…)
mocks
get
accessor函数,因此在返回字符串的同时,一个实现将返回另一个函数

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

jest.spyOn(ConsoleLoggingService, 'error', 'get').mockReturnValue(jest.fn())
...
expect(ConsoleLoggingService.error).toBeCalledWith(...)
使用
get
效率较低,因为函数在每次
错误访问时都会绑定。可以简化为:

static error = console.error.bind(console, 'Error: ')
并嘲笑为:

jest.spyOn(ConsoleLoggingService, 'error').mockImplementation(() => {})

为什么它需要是访问器?
ConsoleLoggingService.error
是否可以直接作为函数?@PedroMutter是的,我认为这太复杂了,但我试图避免修改代码(正在工作)以执行单元测试。我明白了。。。您可以尝试模拟整个文件
jest.mock('path/to/ConsoleLoggingService')
。然后他们导入它并更改
beforeAll
hook中
error
的值。比如
ConsoleLoggingService.error=jest.fn()
不工作。我得到一个TS错误
无法分配给“error”,因为它是只读属性