8

I'm currently working on a project where I'm using Jest for unit testing and code coverage.

Everything is working fine, except coverage for mocked classes/methods. I don't seem to get the desired coverage results. I've tried to find something in the Jest docs and searched online for an answer, but I can't seem to find anything about it.

The thing is that when I use a mocked implementation (for example ./services/__mocks__/UserService.js), the actual implementation (./services/UserService.js) results in having 0% coverage. This is a logical outcome, since the implementation is overwritten by the mock.

I can get around this by using /* istanbul ignore next */ on every method in the actual service or simply add the actual services to the coveragePathIgnorePatterns property in the Jest setup file and let it generate coverage for all mocked classes instead, but I wonder if there is any way to have Jest use the mocked implementation automatically for generating coverage results.

What is the way to go for mocked classes/functions and code coverage?

Thanks in advance!

  • 2
    Typically a service like `UserService.js` will be mocked in the unit tests for code that depends on it, but will also have its own unit tests that ensure it works properly. – Brian Adams Apr 23 '19 at 04:13

1 Answers1

1

As in documentation says for manual mocks, you'll use ./services/__mocks__/UserService.js only if you explicitly called something like jest.mock('./services/UserService');.

If you want to write tests for ./services/UserService, be convinced you don't use jest.mock('./services/UserService'); before this tests.

hal
  • 1,705
  • 1
  • 22
  • 28
  • 2
    Within OP's description, they mention: "Everything is working fine, except coverage for mocked classes/methods" I personally am curious how I can mock a method (e.g. with jest.fn() ) but then have jest not feel the need to tell me that I'm missing coverage for that method) I have a method in a Vue component that handles an event which I'm already testing for sufficiently, and I feel that adding another unit test to directly test against that method is adding unnecessary coupling with no additional benefit. – CaffeinateOften Apr 24 '19 at 21:30
  • 1
    Just logged in again and noticed this. Nowadays I'm much more aware of how this works and I shouldn't mock the things I want coverage for. I'm defining mocks for modules using jest.mock now, so everything that is imported in the actual services contain the mocks I need. Works perfectly now. Thanks for the answer though. – Jeffrey van den Wijngaard Nov 10 '20 at 09:30