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

这就是我正在覆盖的功能,但是仍然抱怨我没有覆盖之前的第4行。npm run coverage


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)}>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({});

    });

});

我正在测试点击道具的不同状态,但是到目前为止还无法覆盖该行,这里有任何想法吗?


慕工程0101907
浏览 132回答 1
1回答

潇潇雨雨

如果你稍微重构一下,你可以看到哪一行没有被调用:export const CardContainer = ({ index, icon, copy, click }) => (&nbsp; <BlankCard variant="light" title={copy}>{icon}<p>{copy}</p>&nbsp; &nbsp; &nbsp; {click && <a className="tile-learn-more" id={`tile-id-${index}`} onClick={() => {&nbsp; &nbsp; &nbsp; &nbsp; click(index);&nbsp; // this one!&nbsp; &nbsp; &nbsp; }}>Learn More</a>}&nbsp; </BlankCard>);该行未被覆盖,因为从未实际调用回调。onClick此外,仅仅测试任何函数是否绑定到它并不是很有用 - 绑定到一个no-op,比如,甚至绑定到错误的函数,仍然会通过。这也是在测试实现,而不是行为。onClick={() => {}}相反,模拟点击并确保模拟被调用:it('will do the right thing when the Learn More link is clicked', () => {&nbsp; &nbsp; const mockOnClick = jest.fn();&nbsp; &nbsp; const index = 1;&nbsp; &nbsp; const props = { index, icon: 'icon', copy: 'foo', click: mockOnClick };&nbsp; &nbsp; const wrapper = shallow(<CardContainer {...props} />);&nbsp; &nbsp; wrapper.find('.tile-learn-more').simulate('click');&nbsp; &nbsp; expect(mockOnClick).toHaveBeenCalledWith(index);});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript