javascript 对象中的test元素为空,带有jest

mjqavswn  于 2023-02-02  发布在  Java
关注(0)|答案(2)|浏览(132)

我有这段代码,npm运行测试给予了我一个关于覆盖率的问题。我看到覆盖率的html,我看到我的解构,url =''显示为黄色。
我看到了问题所在,我看到了这个:

function Team(props) {
  const { team } = props;
  const {
    url = '', //this element appear in yellow, so is not being testing.
  } = team;
  const context = useAppContext();
  const { sportEvent, protocol } = getProperties(context);
  const { arcSite, outputType } = context;
  const basePath = getBasePath(context);
  const infoTeamPicture = translateMessage({ arcSite, id: 'infoCard.infoTeamPicture', defaultMessage: 'Escudo/Bandera equipo' });
  const initPath = getInitPath(team, protocol, basePath);
  return (
    outputType === 'amp' ?
      <TeamAmp infoTeamPicture={infoTeamPicture} team={team} initPath={initPath}/>
      :
      <figure className="ext ext-ic ext-ic--team">
        <div className="ext-ic__wr" {...getDTMRegion(ACTIVITY_MAP_NAME)}>
          <a href={`${initPath}${url}`} className="ext-ic__img">
            <img
              src={`${sportEvent.host}${team.image60}`}
              alt={infoTeamPicture}
              width="80"
              height="80"
            />
          </a>
            <div className="ext-ic__inf">
                <a href={`${initPath}${url}`} title={team.shortName} className="ext-ic__tl"><span>{team.shortName}</span></a>
                <InfoList team={team} />
            </div>
            <InfoButtons protocol={protocol} info={team} initPath={initPath}/>
        </div>
        {team.competition && <Competition competition={team.competition} />}
      </figure>
  );
}

我尝试创建一个新测试,如下所示:

it('no render url', () => {
    const specificTeams = {
      shortName: 'Real Madrid',
      country: 'España',
      url: '',
      urlTag: 'as.com/m/tag/real_madrid/a?omnil=src-app',
      image60: '/img/comunes/fotos/fichas/equipos/small/2x/1.png',
      image100: '/img/comunes/fotos/fichas/equipos/large/1.png',
      elementType: 'team',
      competition: {
        name: 'LaLiga Santander 2020/2021',
        normalized: 'primera',
        standing: [],
        nextGames: {},
      },
    };
    const instance = shallow(<Team team={specificTeams}/>);
    expect(specificTeams.url).toEqual('')
  });

但是我不能达到100%的覆盖率。有人能帮我了解如何测试这种东西吗?谢谢

bvhaajcl

bvhaajcl1#

我确实找到了一个有效的解决方案。在我的例子中,我需要在我的测试中传递一个空对象,以检查真实的代码中的空对象。
就像这样:

it('no render url', () => {
    const specificTeams = {          
      url: '', 
      },
    };
    const instance = shallow(<Team team={specificTeams}/>);
     expect(instance).toBeDefined();
  });

另一种方法是传递一个完全空的对象,但是有时候测试会给你一个错误,一个关于对象的未定义的消息。

cld4siwp

cld4siwp2#

你可以用JSON.stringify来实现,因为它会返回**'{}'**字符串。单元测试将是:

expect(JSON.stringify(someObject)).toBe('{}');

相关问题