Home > Enterprise >  Why does jest consider whole functions as "not covered branches" when reporting test cover
Why does jest consider whole functions as "not covered branches" when reporting test cover

Time:10-14

I am working on a CRA repo and I am adding tests.

I am facing the issue that Jest reports whole functions as not covered branches; functions that have otherwise no branching logic at all.

e.g.

import { useCallback, useState } from 'react';

function useToggleModal(initialState = false) {
  const [isOpen, setIsOpen] = useState<boolean>(initialState);

  const handleOpenModal = useCallback(() => setIsOpen(true), []);
  const handleCloseModal = useCallback(() => setIsOpen(false), []);

  return { isOpen, handleOpenModal, handleCloseModal };
}

export default useToggleModal;

This is a straightforward function, yet, while every other test metric for it is at 100%, branch coverage sits at 0%, reporting line 3 (the start of the function declaration) as the uncovered branch, which makes no sense.

I have many other such cases among my tests and this behaviour is tanking my branch coverage % for no apparent reason.

Changing the coverageProvider option to v8 instead of babel seems to generate correct reports, at least for such cases which I know are reported wrong when using babel as a coverage provider. I am hesitant as to whether I should keep v8 though since there are some issues with it

https://jestjs.io/docs/configuration#coverageprovider-string

CodePudding user response:

Well, turns out the function accepting an optional argument is considered a branch, so I needed to have a test that does not pass an argument

  • Related