首页 > 解决方案 > 无法涵盖具有 props 的 React 组件的单元测试用例

问题描述

我有一个包含以下代码的组件:-

import React from "react";
import { Box, Grid } from "@material-ui/core";
import ArrowBackIosIcon from "@material-ui/icons/ArrowBackIos";
import SearchOutlinedIcon from "@material-ui/icons/SearchOutlined";
import blue from "@material-ui/core/colors/blue";
const BackwithSearchIcon = (props) => {
    const blue_900 = blue[900];
    const searchOption = ()=>{
            return (props.searchOption)?(
                <Grid item>
                    <Box mr={2}>
                        <SearchOutlinedIcon color="primary" />
                    </Box>
                </Grid>    
            ):(null)
    }
 
    return (
        <Grid container>
            <Grid item>
              <Box>
                <ArrowBackIosIcon
                  color="primary"
                  onClick={()=>props.goBack()}
                />
              </Box>
            </Grid>
            <Grid item xs>
              <Box
                component="span"
                fontSize={18}
                fontWeight="fontWeightMedium"
                color={blue_900}
                onClick={()=>props.goBack()}
              >
                Back
              </Box>
            </Grid>
            {searchOption()}
        </Grid>
    )
}

export default BackwithSearchIcon;

我正在使用以下代码编写单元测试用例:-

test('renders as expected', () => {
    const goBack = () => {}
    const renderer = new ShallowRenderer()
    const result=(<BackwithSearchIcon searchOption={true} goBack = {goBack}></BackwithSearchIcon>)
    expect(result.props.searchOption).toBe(true);
});

当我生成覆盖率报告时,报表没有被覆盖。覆盖率为 14% 覆盖率报告

我正在渲染整个组件,我尝试将 searchOption 发送为 false,但百分比仍然不起作用

标签: reactjsreact-routerjestjsreact-testing-libraryreact-test-renderer

解决方案


推荐阅读