lmalves
lmalves

Reputation: 169

Mock static getter with jest

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

Upvotes: 4

Views: 6188

Answers (1)

Estus Flask
Estus Flask

Reputation: 222498

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(() => {})

Upvotes: 7

Related Questions