玩笑测试:react propTypes / defaultProps 的覆盖率

时间:2021-03-08 15:28:28

标签: reactjs jestjs react-proptypes

我有一个愚蠢的组件,我传递的道具很少。我也在使用 PropTypes。

当我运行 jest test:coverage 时,它​​会显示 % Funcs 100。 但是,当我添加 defaultProps 时,test:coverage for % Funcs 下降到 50。

有没有办法测试 defaultProps 或从 test:coverage chyeck/report 中排除这些?

2 个答案:

答案 0 :(得分:1)

最简单的方法,应该是在 defaultProps 语句上方使用这一行istanbul ignore next

/* istanbul ignore next */
DetailPage.defaultProps = {
  metaData: null
};

答案 1 :(得分:0)

这似乎是伊斯坦布尔的一个持续问题,有一些解决方法(如@jean182 建议的方法)。但是,我想避免从每个文件的 instabul 覆盖范围中排除 defaultProps...

通过像这样测试 defaultProps,我设法获得了 100% 的 Funcs 覆盖率:

WidgetHeader.defaultProps = {
    title: '',
    subtitle: '',
    lastUpdated: '',
    onUpdateClick: () => {}
};

然后为其添加测试:

it( 'should check defaultProps', () => {
    const component = mount( <WidgetHeader /> );

    const props = component.props();

    expect( props.title ).toEqual( '' );
    expect( props.subtitle ).toEqual( '' );
    expect( props.lastUpdated ).toEqual( '' );
    expect( props.onUpdateClick ).not.toThrow();
});

如果这是正确的方法,仍然不是 100%。为每个组件测试 defaultProps 似乎很乏味...... 有人有什么建议吗?

谢谢