Merge pull request #1014 from acelaya-forks/feature/ref-warning-fix

Fix warning in AppUpdateBanner
This commit is contained in:
Alejandro Celaya 2023-12-31 20:18:53 +01:00 committed by GitHub
commit a702635294
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 64 additions and 58 deletions

View file

@ -1,7 +1,8 @@
import { faSyncAlt as reloadIcon } from '@fortawesome/free-solid-svg-icons'; import { faSyncAlt as reloadIcon } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { SimpleCard, useToggle } from '@shlinkio/shlink-frontend-kit'; import { SimpleCard, useToggle } from '@shlinkio/shlink-frontend-kit';
import type { FC, MouseEventHandler } from 'react'; import type { MouseEventHandler } from 'react';
import { forwardRef, useCallback } from 'react';
import { Alert, Button } from 'reactstrap'; import { Alert, Button } from 'reactstrap';
import './AppUpdateBanner.scss'; import './AppUpdateBanner.scss';
@ -11,15 +12,15 @@ interface AppUpdateBannerProps {
forceUpdate: Function; forceUpdate: Function;
} }
export const AppUpdateBanner: FC<AppUpdateBannerProps> = ({ isOpen, toggle, forceUpdate }) => { export const AppUpdateBanner = forwardRef<HTMLElement, AppUpdateBannerProps>(({ isOpen, toggle, forceUpdate }, ref) => {
const [isUpdating,, setUpdating] = useToggle(); const [isUpdating,, setUpdating] = useToggle();
const update = () => { const update = useCallback(() => {
setUpdating(); setUpdating();
forceUpdate(); forceUpdate();
}; }, [forceUpdate, setUpdating]);
return ( return (
<Alert className="app-update-banner" isOpen={isOpen} toggle={toggle} tag={SimpleCard} color="secondary"> <Alert className="app-update-banner" isOpen={isOpen} toggle={toggle} tag={SimpleCard} color="secondary" innerRef={ref}>
<h4 className="mb-4">This app has just been updated!</h4> <h4 className="mb-4">This app has just been updated!</h4>
<p className="mb-0"> <p className="mb-0">
Restart it to enjoy the new features. Restart it to enjoy the new features.
@ -30,4 +31,4 @@ export const AppUpdateBanner: FC<AppUpdateBannerProps> = ({ isOpen, toggle, forc
</p> </p>
</Alert> </Alert>
); );
}; });

View file

@ -1,4 +1,4 @@
import { render, screen } from '@testing-library/react'; import { act, render, screen } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn'; import { fromPartial } from '@total-typescript/shoehorn';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { AppFactory } from '../../src/app/App'; import { AppFactory } from '../../src/app/App';
@ -17,26 +17,25 @@ describe('<App />', () => {
ShlinkVersionsContainer: () => <>ShlinkVersions</>, ShlinkVersionsContainer: () => <>ShlinkVersions</>,
}), }),
); );
const setUp = (activeRoute = '/') => render( const setUp = async (activeRoute = '/') => act(() => render(
<MemoryRouter initialEntries={[{ pathname: activeRoute }]}> <MemoryRouter initialEntries={[{ pathname: activeRoute }]}>
<App <App
fetchServers={() => {}} fetchServers={() => {}}
servers={{}} servers={{}}
settings={fromPartial({})} settings={fromPartial({})}
appUpdated appUpdated={false}
resetAppUpdate={() => {}} resetAppUpdate={() => {}}
/> />
</MemoryRouter>, </MemoryRouter>,
); ));
it('passes a11y checks', () => checkAccessibility(setUp())); it('passes a11y checks', () => checkAccessibility(setUp()));
it('renders children components', () => { it('renders children components', async () => {
setUp(); await setUp();
expect(screen.getByText('MainHeader')).toBeInTheDocument(); expect(screen.getByText('MainHeader')).toBeInTheDocument();
expect(screen.getByText('ShlinkVersions')).toBeInTheDocument(); expect(screen.getByText('ShlinkVersions')).toBeInTheDocument();
expect(screen.getByText('This app has just been updated!')).toBeInTheDocument();
}); });
it.each([ it.each([
@ -50,16 +49,16 @@ describe('<App />', () => {
['/server/def456/bar', 'ShlinkWebComponentContainer'], ['/server/def456/bar', 'ShlinkWebComponentContainer'],
['/other', 'Oops! We could not find requested route.'], ['/other', 'Oops! We could not find requested route.'],
])('renders expected route', async (activeRoute, expectedComponent) => { ])('renders expected route', async (activeRoute, expectedComponent) => {
setUp(activeRoute); await setUp(activeRoute);
expect(await screen.findByText(expectedComponent)).toBeInTheDocument(); expect(screen.getByText(expectedComponent)).toBeInTheDocument();
}); });
it.each([ it.each([
['/foo', 'shlink-wrapper'], ['/foo', 'shlink-wrapper'],
['/bar', 'shlink-wrapper'], ['/bar', 'shlink-wrapper'],
['/', 'shlink-wrapper d-flex d-md-block align-items-center'], ['/', 'shlink-wrapper d-flex d-md-block align-items-center'],
])('renders expected classes on shlink-wrapper based on current pathname', (pathname, expectedClasses) => { ])('renders expected classes on shlink-wrapper based on current pathname', async (pathname, expectedClasses) => {
const { container } = setUp(pathname); const { container } = await setUp(pathname);
const shlinkWrapper = container.querySelector('.shlink-wrapper'); const shlinkWrapper = container.querySelector('.shlink-wrapper');
expect(shlinkWrapper).toHaveAttribute('class', expectedClasses); expect(shlinkWrapper).toHaveAttribute('class', expectedClasses);

View file

@ -1,4 +1,4 @@
import { screen } from '@testing-library/react'; import { act, screen, waitFor } from '@testing-library/react';
import { AppUpdateBanner } from '../../src/common/AppUpdateBanner'; import { AppUpdateBanner } from '../../src/common/AppUpdateBanner';
import { checkAccessibility } from '../__helpers__/accessibility'; import { checkAccessibility } from '../__helpers__/accessibility';
import { renderWithEvents } from '../__helpers__/setUpTest'; import { renderWithEvents } from '../__helpers__/setUpTest';
@ -6,12 +6,19 @@ import { renderWithEvents } from '../__helpers__/setUpTest';
describe('<AppUpdateBanner />', () => { describe('<AppUpdateBanner />', () => {
const toggle = vi.fn(); const toggle = vi.fn();
const forceUpdate = vi.fn(); const forceUpdate = vi.fn();
const setUp = () => renderWithEvents(<AppUpdateBanner isOpen toggle={toggle} forceUpdate={forceUpdate} />); const setUp = async () => {
const result = await act(
() => renderWithEvents(<AppUpdateBanner isOpen toggle={toggle} forceUpdate={forceUpdate} />),
);
await waitFor(() => screen.getByRole('alert'));
return result;
};
it('passes a11y checks', () => checkAccessibility(setUp())); it('passes a11y checks', () => checkAccessibility(setUp()));
it('renders initial state', () => { it('renders initial state', async () => {
setUp(); await setUp();
expect(screen.getByRole('heading')).toHaveTextContent('This app has just been updated!'); expect(screen.getByRole('heading')).toHaveTextContent('This app has just been updated!');
expect(screen.queryByText('Restarting...')).not.toBeInTheDocument(); expect(screen.queryByText('Restarting...')).not.toBeInTheDocument();
@ -19,7 +26,7 @@ describe('<AppUpdateBanner />', () => {
}); });
it('invokes toggle when alert is closed', async () => { it('invokes toggle when alert is closed', async () => {
const { user } = setUp(); const { user } = await setUp();
expect(toggle).not.toHaveBeenCalled(); expect(toggle).not.toHaveBeenCalled();
await user.click(screen.getByLabelText('Close')); await user.click(screen.getByLabelText('Close'));
@ -27,7 +34,7 @@ describe('<AppUpdateBanner />', () => {
}); });
it('triggers the update when clicking the button', async () => { it('triggers the update when clicking the button', async () => {
const { user } = setUp(); const { user } = await setUp();
expect(forceUpdate).not.toHaveBeenCalled(); expect(forceUpdate).not.toHaveBeenCalled();
await user.click(screen.getByText(/^Restart now/)); await user.click(screen.getByText(/^Restart now/));

View file

@ -1,4 +1,4 @@
import { screen, waitFor } from '@testing-library/react'; import { act, screen, waitFor } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn'; import { fromPartial } from '@total-typescript/shoehorn';
import { createMemoryHistory } from 'history'; import { createMemoryHistory } from 'history';
import { Router } from 'react-router-dom'; import { Router } from 'react-router-dom';
@ -10,37 +10,36 @@ import { TestModalWrapper } from '../__helpers__/TestModalWrapper';
describe('<DeleteServerModal />', () => { describe('<DeleteServerModal />', () => {
const deleteServerMock = vi.fn(); const deleteServerMock = vi.fn();
const serverName = 'the_server_name'; const serverName = 'the_server_name';
const setUp = () => { const setUp = async () => {
const history = createMemoryHistory({ initialEntries: ['/foo'] }); const history = createMemoryHistory({ initialEntries: ['/foo'] });
return { const result = await act(() => renderWithEvents(
history, <Router location={history.location} navigator={history}>
...renderWithEvents( <TestModalWrapper
<Router location={history.location} navigator={history}> renderModal={(args) => (
<TestModalWrapper <DeleteServerModal
renderModal={(args) => ( {...args}
<DeleteServerModal server={fromPartial({ name: serverName })}
{...args} deleteServer={deleteServerMock}
server={fromPartial({ name: serverName })} />
deleteServer={deleteServerMock} )}
/> />
)} </Router>,
/> ));
</Router>,
), return { history, ...result };
};
}; };
it('passes a11y checks', () => checkAccessibility(setUp())); it('passes a11y checks', () => checkAccessibility(setUp()));
it('renders a modal window', () => { it('renders a modal window', async () => {
setUp(); await setUp();
expect(screen.getByRole('dialog')).toBeInTheDocument(); expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByRole('heading')).toHaveTextContent('Remove server'); expect(screen.getByRole('heading')).toHaveTextContent('Remove server');
}); });
it('displays the name of the server as part of the content', () => { it('displays the name of the server as part of the content', async () => {
setUp(); await setUp();
expect(screen.getByText(/^Are you sure you want to remove/)).toBeInTheDocument(); expect(screen.getByText(/^Are you sure you want to remove/)).toBeInTheDocument();
expect(screen.getByText(serverName)).toBeInTheDocument(); expect(screen.getByText(serverName)).toBeInTheDocument();
@ -50,7 +49,7 @@ describe('<DeleteServerModal />', () => {
[() => screen.getByRole('button', { name: 'Cancel' })], [() => screen.getByRole('button', { name: 'Cancel' })],
[() => screen.getByLabelText('Close')], [() => screen.getByLabelText('Close')],
])('toggles when clicking cancel button', async (getButton) => { ])('toggles when clicking cancel button', async (getButton) => {
const { user, history } = setUp(); const { user, history } = await setUp();
expect(history.location.pathname).toEqual('/foo'); expect(history.location.pathname).toEqual('/foo');
await user.click(getButton()); await user.click(getButton());
@ -60,7 +59,7 @@ describe('<DeleteServerModal />', () => {
}); });
it('deletes server when clicking accept button', async () => { it('deletes server when clicking accept button', async () => {
const { user, history } = setUp(); const { user, history } = await setUp();
expect(deleteServerMock).not.toHaveBeenCalled(); expect(deleteServerMock).not.toHaveBeenCalled();
expect(history.location.pathname).toEqual('/foo'); expect(history.location.pathname).toEqual('/foo');

View file

@ -1,4 +1,4 @@
import { screen } from '@testing-library/react'; import { act, screen } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn'; import { fromPartial } from '@total-typescript/shoehorn';
import type { ServerData } from '../../../src/servers/data'; import type { ServerData } from '../../../src/servers/data';
import { DuplicatedServersModal } from '../../../src/servers/helpers/DuplicatedServersModal'; import { DuplicatedServersModal } from '../../../src/servers/helpers/DuplicatedServersModal';
@ -8,9 +8,9 @@ import { renderWithEvents } from '../../__helpers__/setUpTest';
describe('<DuplicatedServersModal />', () => { describe('<DuplicatedServersModal />', () => {
const onDiscard = vi.fn(); const onDiscard = vi.fn();
const onSave = vi.fn(); const onSave = vi.fn();
const setUp = (duplicatedServers: ServerData[] = []) => renderWithEvents( const setUp = (duplicatedServers: ServerData[] = []) => act(() => renderWithEvents(
<DuplicatedServersModal isOpen duplicatedServers={duplicatedServers} onDiscard={onDiscard} onSave={onSave} />, <DuplicatedServersModal isOpen duplicatedServers={duplicatedServers} onDiscard={onDiscard} onSave={onSave} />,
); ));
const mockServer = (data: Partial<ServerData> = {}) => fromPartial<ServerData>(data); const mockServer = (data: Partial<ServerData> = {}) => fromPartial<ServerData>(data);
it('passes a11y checks', () => checkAccessibility(setUp())); it('passes a11y checks', () => checkAccessibility(setUp()));
@ -21,8 +21,8 @@ describe('<DuplicatedServersModal />', () => {
[[mockServer(), mockServer()], 2], [[mockServer(), mockServer()], 2],
[[mockServer(), mockServer(), mockServer()], 3], [[mockServer(), mockServer(), mockServer()], 3],
[[mockServer(), mockServer(), mockServer(), mockServer()], 4], [[mockServer(), mockServer(), mockServer(), mockServer()], 4],
])('renders expected amount of items', (duplicatedServers, expectedItems) => { ])('renders expected amount of items', async (duplicatedServers, expectedItems) => {
setUp(duplicatedServers); await setUp(duplicatedServers);
expect(screen.queryAllByRole('listitem')).toHaveLength(expectedItems); expect(screen.queryAllByRole('listitem')).toHaveLength(expectedItems);
}); });
@ -45,8 +45,8 @@ describe('<DuplicatedServersModal />', () => {
discardBtn: 'Ignore duplicates', discardBtn: 'Ignore duplicates',
}, },
], ],
])('renders expected texts based on amount of servers', (duplicatedServers, assertions) => { ])('renders expected texts based on amount of servers', async (duplicatedServers, assertions) => {
setUp(duplicatedServers); await setUp(duplicatedServers);
expect(screen.getByRole('heading')).toHaveTextContent(assertions.header); expect(screen.getByRole('heading')).toHaveTextContent(assertions.header);
expect(screen.getByText(assertions.firstParagraph)).toBeInTheDocument(); expect(screen.getByText(assertions.firstParagraph)).toBeInTheDocument();
@ -61,8 +61,8 @@ describe('<DuplicatedServersModal />', () => {
mockServer({ url: 'url_1', apiKey: 'apiKey_1' }), mockServer({ url: 'url_1', apiKey: 'apiKey_1' }),
mockServer({ url: 'url_2', apiKey: 'apiKey_2' }), mockServer({ url: 'url_2', apiKey: 'apiKey_2' }),
]], ]],
])('displays provided server data', (duplicatedServers) => { ])('displays provided server data', async (duplicatedServers) => {
setUp(duplicatedServers); await setUp(duplicatedServers);
if (duplicatedServers.length === 0) { if (duplicatedServers.length === 0) {
expect(screen.queryByRole('listitem')).not.toBeInTheDocument(); expect(screen.queryByRole('listitem')).not.toBeInTheDocument();
@ -81,7 +81,7 @@ describe('<DuplicatedServersModal />', () => {
}); });
it('invokes onDiscard when appropriate button is clicked', async () => { it('invokes onDiscard when appropriate button is clicked', async () => {
const { user } = setUp(); const { user } = await setUp();
expect(onDiscard).not.toHaveBeenCalled(); expect(onDiscard).not.toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: 'Discard' })); await user.click(screen.getByRole('button', { name: 'Discard' }));
@ -89,7 +89,7 @@ describe('<DuplicatedServersModal />', () => {
}); });
it('invokes onSave when appropriate button is clicked', async () => { it('invokes onSave when appropriate button is clicked', async () => {
const { user } = setUp(); const { user } = await setUp();
expect(onSave).not.toHaveBeenCalled(); expect(onSave).not.toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: 'Save anyway' })); await user.click(screen.getByRole('button', { name: 'Save anyway' }));