I'm trying to mock a logging service that have static getters.
static get error(): Function {
return console.error.bind(console, 'Error: ');
}
Tried with:
jest.spyOn(ConsoleLoggingService, 'error').mockImplementation(() => 'blah');
but I get TypeError: Cannot set property info of function ConsoleLoggingService() {} which has only a getter
Also tried:
jest.spyOn(ConsoleLoggingService, 'error', 'get').mockImplementation(() => 'blah');
And get TypeError: console_logging_service_1.ConsoleLoggingService.error is not a function
Any suggestions?
Thanks
jest.spyOn(ConsoleLoggingService, 'error', 'get').mockImplementation(() => ...) mocks get accessor function, so an implementation is expected to return another function, while a string is returned.
It can return another spy for testing purposes:
jest.spyOn(ConsoleLoggingService, 'error', 'get').mockReturnValue(jest.fn())
...
expect(ConsoleLoggingService.error).toBeCalledWith(...)
The use of get is less efficient because the function is bound on every error access. It could be simplified to:
static error = console.error.bind(console, 'Error: ')
And mocked as:
jest.spyOn(ConsoleLoggingService, 'error').mockImplementation(() => {})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With