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!
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.
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.
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).
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.
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.
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