Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Jest to have coverage for export only lines?

I have an index.ts top file in an NPM library which has only export statements.

i.e.:

export * from "./foo"
export * from "./bar"

SonarCloud is showing those lines as not covered, as it is expected that those should have no tests. I know we can live with the missing coverage but it is somehow annoying.

I know I could also ignore the file, but then I would need to do the same for every file with a similar purpose that group and export components down inside the library.

Is there any best practice or configuration I can use to overcome that?

like image 953
Felipe Plets Avatar asked Oct 26 '25 09:10

Felipe Plets


1 Answers

After some research I found an option that is aligned with what I was looking for.

Mocha

This is inspired by MaterialUI repo which uses mocha with chai:

import { expect } from 'chai';
import * as MyLib from './index';

describe('MyLib', () => {
  it('should have exports', () => {
    expect(typeof MyLib).to.equal('object');
  });

  it('should not have undefined exports', () => {
    Object.keys(MyLib).forEach((exportKey) =>
      expect(Boolean(MyLib[exportKey])).to.equal(true),
    );
  });
});

source: https://github.com/mui-org/material-ui/blob/next/packages/material-ui/src/index.test.js

JEST

As we use JEST in my project we had to convert it:

import * as MyLib from './index';

describe('MyLib', () => {
  it('should have exports', () => {
    expect(MyLib).toEqual(expect.any(Object));
  });

  it('should not have undefined exports', () => {
    for (const k of Object.keys(MyLib))
      expect(MyLib).not.toHaveProperty(k, undefined);
  });
});
like image 73
Felipe Plets Avatar answered Oct 27 '25 23:10

Felipe Plets



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!