Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest - How to get coverage for mocked classes and implementations

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!

like image 596
Jeffrey van den Wijngaard Avatar asked May 15 '18 10:05

Jeffrey van den Wijngaard


People also ask

How do I get Jest coverage?

To get Jest up & running, install it as a dev dependency in your project. For ease of use, also in your CI/CD pipelines, I recommend to add script entries for running Jest with and without collecting coverage statistics in your package.

What is __ mocks __ in Jest?

In Jest, Node. js modules are automatically mocked in your tests when you place the mock files in a __mocks__ folder that's next to the node_modules folder. For example, if you a file called __mock__/fs. js , then every time the fs module is called in your test, Jest will automatically use the mocks.

Does Jest mock get hoisted?

Using with ES module imports​ But often you need to instruct Jest to use a mock before modules use it. For this reason, Jest will automatically hoist jest. mock calls to the top of the module (before any imports).

How do you use spyOn function in Jest?

To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.


1 Answers

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.

like image 53
hal Avatar answered Nov 15 '22 07:11

hal