我有一个组件,当我用测试覆盖它时-覆盖率不是100%,因为默认属性函数没有覆盖
Favorites.defaultProps = {
toggleFavorite: () => {} - is NOT COVERED
};
字符串
我不知道如何测试默认的prop函数,因为我已经测试了click事件,并且已经调用了toggleFavorite()函数。请参阅第一个测试handles toggle favorite
。因此在这个测试中,我调用了该函数。
请告诉我我做错了什么,为什么覆盖率不是100%。
我的组件:
export const Favorites = ({ id, metadata, toggleFavorite, isFavorite }) => {
const [isFavorites, setIsFavorites] = React.useState(isFavorite);
useEffect(() => {
setIsFavorites(isFavorite);
}, [isFavorite]);
const toggleFavoriteStatus = () => {
setIsFavorites(!isFavorites);
const { cmosCatalogId, cmosItem } = metadata;
toggleFavorite({ id, cmosCatalogId, cmosItem }, isFavorites);
};
return (
<Container>
<FavButton
aria-label={isFavorites ? 'Remove from favorites' : 'Add to favorites'}
onClick={toggleFavoriteStatus}
data-testid="favorite-button"
>
<FavImage
className="fav-btn-img"
style={{ opacity: isFavorites ? 1 : 0.3 }}
src={isFavorites ? selectedFavIcon : favOverIcon}
alt={favOverIcon}
/>
</FavButton>
</Container>
);
};
Favorites.propTypes = {
id: PropTypes.string,
metadata: PropTypes.object,
isFavorite: PropTypes.any,
toggleFavorite: PropTypes.func,
};
Favorites.defaultProps = {
id: '',
metadata: {},
isFavorite: false,
toggleFavorite: () => {},
};
型
测试:
describe('Favorites component', () => {
it('handles toggle favorite', () => {
const props = getProps();
const { container } = render(<Favorites {...props} />);
const { cmosCatalogId, cmosItem } = props.metadata;
const { id } = props;
fireEvent.click(queryByTestId(container, 'favorite-button'));
expect(props.toggleFavorite).toHaveBeenCalled();
expect(props.toggleFavorite).toHaveBeenCalledWith({ id, cmosCatalogId, cmosItem }, props.isFavorite);
});
it('should have aria-label equals to Add to favorites if isFavorite is false', () => {
const props = getProps({
isFavorite: false,
});
const { container } = render(<Favorites {...props} />);
expect(queryByTestId(container, 'favorite-button').getAttribute('aria-label')).toBe('Add to favorites');
});
it('should have aria-label equals to Remove from favorites if isFavorite is true', () => {
const props = getProps({
isFavorite: true,
});
const { container } = render(<Favorites {...props} />);
expect(queryByTestId(container, 'favorite-button').getAttribute('aria-label')).toBe('Remove from favorites');
});
});
型
2条答案
按热度按时间up9lanfz1#
您需要编写一个测试,在没有传入
toggleFavorite
属性的情况下呈现组件;这样,当调用toggleFavoriteStatus时,Favorites.defaultProps.toggleFavorite
将被调用字符串
avkwfej42#
请尝试窥探默认 prop 函数,然后调用单击.用这种方法,我们可以Assert默认函数调用/调用参数.我也,没有运气与覆盖率报告,即使在执行下面的代码不幸.
字符串