28
loading...
This website collects cookies to deliver better user experience
import React from 'react';
const Footer = ({ links }) => {
// handles the number of links to show
const [linksLength, setlinksLength] = React.useState(2);
// handles the button text
const buttonText = linksLength === 2 ? 'View more' : 'View less';
// handles the links to show, if the number > 2 it
const socialLinks = links.filter((item, index) => index <= socialLength);
const handleClick = () => {
setSocialLength(socialLength === links.length ? 2 : links.len)
}
return (
<div>
<h4>Site Links</h4>
<ul>
{socialLinks.map(({ siteLink, siteName }) =>
(
<li key={siteLink}>
<a href={siteLink}>
{siteName}
</a>
</li>
))}
</ul>
<button onClick={() => handleClick()}>{buttonText}</button>
</div>
)
describe('<Footer/>', () => { // this is a style I like just preference
const setup = overrides => {
const props = {
links: ['link-one', 'link-two', 'link-three', 'link-four']
...overrides
}
const R = render(<Footer {...props}/>)
return {
...R,
props
}
}
it('toggles button text between "view more" and "view less"', () => {
const {
queryByText, getByText, getByRole
} = setup();
expect(getByText(/View more/i)).toBeInTheDocument();
expect(queryByText(/View less/i)).not.toBeInTheDocument();
userEvent.click(getByRole('button'));
expect(getByText(/View less/i)).toBeInTheDocument();
expect(queryByText(/View more/i)).not.toBeInTheDocument();
})
})
it('shows three links by default', () => {
const mockLinks = ['One', 'Two', 'Three', 'Four'];
const { queryByText } = setup({links: mockLinks});
expect(queryByText(/Four/i)).not.toBeInTheDocument();
})
it('more than three links are rendered on click', () => {
const mockLinks = ['One', 'Two', 'Three', 'Four'];
const {
queryByText, getByText, getByRole
} = setup({links: mockLinks});
expect(queryByText(/Four/i)).not.toBeInTheDocument();
userEvent.click(getByRole('button'));
expect(getByText(/Four/i)).toBeInTheDocument();
})
getByText(/View more/i)
for that. But suppose marketing decides they want to change that to Show more
. Your test, for how many links show, fails. It's a little thing, but I think it's nicer. Also, it forces you to make a small react component, rather than some 300 line monstrosity.it('shows no button when there are fewer than 3 links', () => {
const mockLinks = ['One', 'Two'];
const { queryByRole } = setup({links: mockLinks});
expect(queryByRole('button')).not.toBeInTheDocument();
// This is also okay I just wouldn't do it now
// expect(queryByText(/View more/i)).not.toBeInTheDocument();
})