我有一个组件,当我用测试覆盖它时,覆盖率不是100%,因为默认的道具功能没有覆盖
Favorites.defaultProps = {
toggleFavorite: () => {} - is NOT COVERED
};
我不知道如何测试默认的道具函数,因为我已经测试了点击事件,并且已经调用了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');
});
});
您需要编写一个测试,在不传递toggleFavorite
道具的情况下渲染组件;这样,当toggleFavoriteStatus被称为时,Favorites.defaultProps.toggleFavorite
将被调用
const { toggleFavourite: _, ...props } = getProps({
isFavorite: true,
});
const { container } = render(<Favorites {...props} />);