Estus Flask
Estus Flask

Reputation: 222474

Jest/Istanbul coverage for a module that isn't loaded with require

There is foo module which contains lines that cannot be tested when it's loaded as Node.js module:

if (typeof module !== 'object') {
  do.something(); // line shows as uncovered
}
...

This line cannot be normally tested with require('./foo') because module is always truthy and cannot be mocked outside the module without hooking into Node module loader.

So I have to evaluate it without require to have full control over module local variables:

const fooSource = fs.readFileSync(fooPath);
new Function('module', fooSource)();
expect(do.something).toHaveBeenCalled();

This works but this test is ignored by test coverage.

As I understand it, Jest code coverage (Istanbul) hooks into Node.js module loader and decorates module body with coverage statements, e.g.:

if (typeof module !== 'object') {
  cov_v50bukkd.f[2]++;
  do.something(); // shows as uncovered
}

How can the coverage be enabled for this line?

I would prefer not to just mark foo with 100% coverage but make it real coverage if possible, like decorating fooSource with coverage statements manually.

I proceed from the fact that foo source code shouldn't be modified to favour code coverage; it's already testable enough in other respects.

Upvotes: 3

Views: 604

Answers (1)

vorillaz
vorillaz

Reputation: 6276

In such cases, you can explicitly set NODE_ENV=test for your testing suite. Jest automatically sets NODE_ENV as such so you may enforce code coverage as:

if (typeof module !== 'object' || process.NODE_ENV === 'test') {
  do.something(); // line shows as uncovered
}

Upvotes: 1

Related Questions