Migrated NavPills test to react testing library

This commit is contained in:
Alejandro Celaya 2022-06-11 09:14:51 +02:00
parent 84435714f5
commit 59087ced8a

View file

@ -1,20 +1,28 @@
import { shallow } from 'enzyme'; /* eslint-disable no-console */
import { Card, Nav } from 'reactstrap'; import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { NavPillItem, NavPills } from '../../src/utils/NavPills'; import { NavPillItem, NavPills } from '../../src/utils/NavPills';
describe('<NavPills />', () => { describe('<NavPills />', () => {
let originalError: typeof console.error;
beforeEach(() => {
originalError = console.error;
console.error = () => {}; // Suppress errors logged during this test
});
afterEach(() => {
console.error = originalError;
});
it.each([ it.each([
['Foo'], ['Foo'],
[<span key="1">Hi!</span>], [<span key="1">Hi!</span>],
[[<NavPillItem key="1" to="" />, <span key="2">Hi!</span>]], [[<NavPillItem key="1" to="" />, <span key="2">Hi!</span>]],
])('throws error when any of the children is not a NavPillItem', (children) => { ])('throws error when any of the children is not a NavPillItem', (children) => {
expect.assertions(1); expect.assertions(1);
expect(() => render(<NavPills>{children}</NavPills>)).toThrow(
try { 'Only NavPillItem children are allowed inside NavPills.',
shallow(<NavPills>{children}</NavPills>); );
} catch (e: any) {
expect(e.message).toEqual('Only NavPillItem children are allowed inside NavPills.');
}
}); });
it.each([ it.each([
@ -22,20 +30,27 @@ describe('<NavPills />', () => {
[true], [true],
[false], [false],
])('renders provided items', (fill) => { ])('renders provided items', (fill) => {
const wrapper = shallow( const { container } = render(
<NavPills fill={fill}> <MemoryRouter>
<NavPillItem to="1">1</NavPillItem> <NavPills fill={fill}>
<NavPillItem to="2">2</NavPillItem> <NavPillItem to="1">1</NavPillItem>
<NavPillItem to="3">3</NavPillItem> <NavPillItem to="2">2</NavPillItem>
</NavPills>, <NavPillItem to="3">3</NavPillItem>
</NavPills>
</MemoryRouter>,
); );
const card = wrapper.find(Card);
const nav = wrapper.find(Nav);
expect(card).toHaveLength(1); const links = screen.getAllByRole('link');
expect(card.prop('body')).toEqual(true); expect(links).toHaveLength(3);
expect(nav).toHaveLength(1); links.forEach((link, index) => {
expect(nav.prop('pills')).toEqual(true); expect(link).toHaveTextContent(`${index + 1}`);
expect(nav.prop('fill')).toEqual(!!fill); expect(link).toHaveAttribute('href', `/${index + 1}`);
});
if (fill) {
expect(container.querySelector('.nav')).toHaveClass('nav-fill');
} else {
expect(container.querySelector('.nav')).not.toHaveClass('nav-fill');
}
}); });
}); });