为了账号安全,请及时绑定邮箱和手机立即绑定

需要帮助获得1行Jest(React)

需要帮助获得1行Jest(React)

慕工程0101907 2022-08-18 10:26:06
这就是我正在覆盖的功能,但是仍然抱怨我没有覆盖之前的第4行。npm run coverageexport const CardContainer = ({ index, icon, copy, click }) => (    <BlankCard variant="light" title={copy}>{icon}<p>{copy}</p>        {click && <a className="tile-learn-more" id={`tile-id-${index}`} onClick={() => click(index)}>Learn More</a>}    </BlankCard>);有问题的行:{click && <a className="tile-learn-more" id={`tile-id-${index}`} onClick={() => click(index)}>Learn More</a>}describe('CardContainer component', () => {    it('will contain BlankCard component', () => {        const props = { icon: 'icon', copy: 'foo' };        const wrapperBlankCard = shallow(<CardContainer {...props} />);        const blankCard = wrapperBlankCard.find('BlankCard');        expect(blankCard).toHaveLength(1);        expect(blankCard.at(0).prop('variant')).toEqual('light');        expect(blankCard.at(0).prop('title')).toEqual('foo');    });    it('will contain a Learn More link if click contains a function', () => {        const mockOnClick = jest.fn();        const props = { index: 1, icon: 'icon', copy: 'foo', click: mockOnClick };        const wrapper = shallow(<CardContainer {...props} />);        const learnMore = wrapper.find('.tile-learn-more');        expect(learnMore).toEqual({});        expect(learnMore.prop('id')).toEqual('tile-id-1');        expect(learnMore.contains('Learn More'));        expect(learnMore.prop('onClick')).toEqual(expect.any(Function));    });    it('will not contain a Learn More link if click is undefined', () => {        const props = { icon: 'icon', copy: 'foo', click: null };        const wrapper = shallow(<CardContainer {...props} />);        expect(wrapper.find('.tile-learn-more')).toEqual({});    });});我正在测试点击道具的不同状态,但是到目前为止还无法覆盖该行,这里有任何想法吗?
查看完整描述

1 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

如果你稍微重构一下,你可以看到哪一行没有被调用:


export const CardContainer = ({ index, icon, copy, click }) => (

  <BlankCard variant="light" title={copy}>{icon}<p>{copy}</p>

      {click && <a className="tile-learn-more" id={`tile-id-${index}`} onClick={() => {

        click(index);  // this one!

      }}>Learn More</a>}

  </BlankCard>

);

该行未被覆盖,因为从未实际调用回调。onClick


此外,仅仅测试任何函数是否绑定到它并不是很有用 - 绑定到一个no-op,比如,甚至绑定到错误的函数,仍然会通过。这也是在测试实现,而不是行为。onClick={() => {}}


相反,模拟点击并确保模拟被调用:


it('will do the right thing when the Learn More link is clicked', () => {

    const mockOnClick = jest.fn();

    const index = 1;

    const props = { index, icon: 'icon', copy: 'foo', click: mockOnClick };

    const wrapper = shallow(<CardContainer {...props} />);


    wrapper.find('.tile-learn-more').simulate('click');


    expect(mockOnClick).toHaveBeenCalledWith(index);

});


查看完整回答
反对 回复 2022-08-18
  • 1 回答
  • 0 关注
  • 131 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号