React、Enzyme 和 Istanbul - 代码覆盖缺失测试正在执行的函数

React, Enzyme and Istanbul - code coverage missing functions being executed by tests

我正在测试一个具有 3 个函数的 React 组件,我已经编写了使用所有这 3 个函数的测试并且测试通过了,但是在代码覆盖率报告中我只得到了 33%。组件如下。

const AddWidget = ({ }: Props) => {

    var id = generateGuid().slice(0, 8);

    var showWidget = () => {
        document.getElementById(id).style.zIndex = "10";
    }

    var hideWidget = () => {
        document.getElementById(id).style.zIndex = "200";
    }

    return (
        <div onMouseLeave={hideWidget} onMouseEnter={showWidget} className="addWidget" >
            <div className="divide" />
            <div id={id} className="cover" />
            <div>
                <CircularButton type={CircularButtonType.DarkAdd} small={true} />
                <p>Add a widget here</p>
            </div>
        </div>
    );
}

export default AddWidget;

还有我的测试...

import * as React from 'react';
import * as Enzyme from 'enzyme';
import * as Adapter from 'enzyme-adapter-react-16';
import AddWidget from './AddWidget';

Enzyme.configure({ adapter: new Adapter() });

const addWidget = Enzyme.mount(<AddWidget />, { attachTo: document.body });

describe('AddWidget', () => {
    test('renders without crashing', () => {
        expect(addWidget.find(AddWidget).length).toBe(1);
    });

    test('should render parent element with class "addWidget"', () => {
        expect(addWidget.find('div').at(0).hasClass('addWidget')).toBe(true);
    });

    test('should cover component from view when mouse is not hovering', () => {
        addWidget.simulate('mouseEnter');
        addWidget.simulate('mouseLeave');
        var covers = document.getElementsByClassName('cover');
        for (var n = 0; n < covers.length; n++) {
            expect((covers[n] as HTMLElement).style.zIndex).toBe("200");
        }
    });

    test('should show component from view onMouseEnter', () => {
        addWidget.simulate('mouseEnter');
        var covers = document.getElementsByClassName('cover');
        for (var n = 0; n < covers.length; n++) {
            expect((covers[n] as HTMLElement).style.zIndex).toBe("10");
        }
    });
});

测试指定 showWidgethideWidget 函数未被测试,但最后 2 个测试肯定 运行 这些函数,否则测试不会通过。

这是代码覆盖错误吗?是它不喜欢我使用纯 Javascript 函数还是我从根本上误解了函数代码覆盖率?

编辑:覆盖率报告图片如下

我发现了问题所在,我是 运行 使用命令 react-scripts test --coverage --coverageDirectory=output/coverage --coverageReporters text --env=jsdom 进行的测试,该命令更新了 cobertura.xml 文件,但没有更新任何 html。我认为 html 读取了 coberatura 文件并显示了它,但事实并非如此。将 html 标志添加到 coverageReporters 解决了这个问题。