NagRock / ts-mockito

Mocking library for TypeScript
MIT License
969 stars 93 forks source link

Can't spy on console inside an angular service #188

Closed KarmaCop213 closed 4 years ago

KarmaCop213 commented 4 years ago

Inside an angular service I have a function with the following:

  test() {
    const spiedConsole = spy(console)
    console.log("hello")
    expect(capture(spiedConsole.log).first()[0]).toEqual("hello")
    reset(spiedConsole)
  }

When I call that function inside a test, and if I run the tests using the command ng test I get:

    TypeError: Cannot read property 'get' of undefined

      110 |   test() {
      111 |     const spiedConsole = spy(console)
    > 112 |     console.log("hello")
          |             ^
      113 |     expect(capture(spiedConsole.log).first()[0]).toEqual("hello")
      114 |     reset(spiedConsole)
      115 |

If I run using the command jest (which is my test framework) it works fine.

Just for sanity check I tried using jest.spyOn and it worked:

  test() {
     const spiedJestConsole = jest.spyOn(console, "log")
     console.log("hello")
     expect(spiedJestConsole.mock.calls[0][0]).toEqual("hello")
     spiedJestConsole.mockRestore()
  }
NagRock commented 4 years ago

It's not too good idea to spy on global API with ts-mockito. It overrides implementation and can cause unexpected behaviors in other tests when you forgot to store real console implementation and reset it after test. Usually it is good practice to wrap low level API. To have custom logger class that is wrapping global console object and spy on it instead of console from global scope.