Skip to content

Commit

Permalink
restored and fixed tests
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreaCimini90 committed Feb 20, 2025
1 parent 20b6942 commit 4ffa18b
Show file tree
Hide file tree
Showing 8 changed files with 65 additions and 65 deletions.
8 changes: 6 additions & 2 deletions packages/pn-commons/src/components/CodeModal/CodeInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {

import { TextField } from '@mui/material';

import { getLocalizedOrDefaultLabel } from '../../utility/localization.utility';

type Props = {
initialValues: Array<string>;
onChange: (values: Array<string>) => void;
Expand Down Expand Up @@ -126,13 +128,15 @@ const CodeInput = ({ initialValues, isReadOnly, hasError, onChange }: Props) =>
onChange(currentValues);
}, [currentValues]);

const cifre = ['primo', 'secondo', 'terzo', 'quarto', 'ultimo'];
const digits = getLocalizedOrDefaultLabel('common', 'code-modal.digits', undefined, {
returnObjects: true,
});

return (
<Fragment>
{initialValues.map((_value, index) => (
<TextField
aria-label={`input numero ${cifre[index]}`}
aria-label={`${digits[index]}`}
data-testid={`codeInput(${index})`}
autoComplete="off"
key={index}
Expand Down
54 changes: 21 additions & 33 deletions packages/pn-commons/src/components/CodeModal/CodeModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ type Props = {
codeSectionTitle: string;
codeSectionAdditional?: ReactNode;
confirmLabel?: string;
cancelLabel?: string;
cancelCallback?: () => void;
cancelLabel: string;
cancelCallback: () => void;
confirmCallback?: (values: Array<string>) => void;
isReadOnly?: boolean;
error?: { title: string; message: string; hasError: boolean };
Expand All @@ -38,24 +38,6 @@ type ModalHandle = {
updateError: (error: ErrorMessage, codeNotValid: boolean) => void;
};

const RenderCopyToClipboardButton: React.FC<{
isReadOnly: boolean;
initialValues: Array<string>;
}> = ({ isReadOnly, initialValues }) =>
isReadOnly && (
<CopyToClipboardButton
id="copy-code-button"
data-testid="copyCodeButton"
sx={{ mt: 1.5 }}
value={initialValues.join('')}
tooltipTitle={getLocalizedOrDefaultLabel(
'delegations',
'deleghe.code_copied',
'Codice copiato'
)}
/>
);

/**
* This modal allows the user to input a verification code.
* @param title title to show
Expand Down Expand Up @@ -140,7 +122,7 @@ const CodeModal = forwardRef<ModalHandle, Props>(
return (
<PnDialog
open={open}
aria-labelledby={code.length ? 'dialog-title' : ''}
aria-labelledby="dialog-title"
aria-describedby="dialog-description"
data-testid="codeDialog"
disableEscapeKeyDown
Expand All @@ -154,16 +136,24 @@ const CodeModal = forwardRef<ModalHandle, Props>(
<Typography fontSize={16} fontWeight={600}>
{codeSectionTitle}
</Typography>
{codeSectionAdditional && <Box sx={{ mt: 2 }}>{codeSectionAdditional}</Box>}
<Box sx={{ mt: 2 }}>
<CodeInput
initialValues={initialValues}
isReadOnly={isReadOnly}
hasError={internalHasError}
onChange={changeHandler}
/>
{isReadOnly && (
<CopyToClipboardButton
id="copy-code-button"
data-testid="copyCodeButton"
sx={{ mt: 1.5 }}
value={initialValues.join('')}
tooltipTitle={getLocalizedOrDefaultLabel('delegations', 'deleghe.code_copied')}
/>
)}
</Box>
<RenderCopyToClipboardButton initialValues={initialValues} isReadOnly={isReadOnly} />
{codeSectionAdditional && <Box sx={{ mt: 2 }}>{codeSectionAdditional}</Box>}
{internalHasError && (
<Alert id="error-alert" data-testid="errorAlert" severity="error" sx={{ mt: 2 }}>
<AlertTitle id="codeModalErrorTitle" data-testid="CodeModal error title">
Expand All @@ -174,16 +164,14 @@ const CodeModal = forwardRef<ModalHandle, Props>(
)}
</PnDialogContent>
<PnDialogActions>
{cancelLabel && cancelCallback && (
<Button
id="code-cancel-button"
variant="outlined"
onClick={cancelCallback}
data-testid="codeCancelButton"
>
{cancelLabel}
</Button>
)}
<Button
id="code-cancel-button"
variant="outlined"
onClick={cancelCallback}
data-testid="codeCancelButton"
>
{cancelLabel}
</Button>
{confirmLabel && confirmCallback && (
<Button
id="code-confirm-button"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,37 +79,26 @@ describe('CodeInput Component', () => {
<CodeInput initialValues={new Array(5).fill('')} onChange={handleChangeMock} />
);
const codeInputs = getAllByTestId(/code-input-[0-4]/);
// focus on the input
act(() => (codeInputs[2] as HTMLInputElement).focus());
fireEvent.change(codeInputs[2], { target: { value: '3' } });
expect(codeInputs[2]).toHaveValue('3');
await waitFor(() => {
expect(handleChangeMock).toHaveBeenCalledTimes(2);
});
// change the value of the input and check that it is updated correctly
// set the cursor position to the end
act(() => (codeInputs[2] as HTMLInputElement).focus());
(codeInputs[2] as HTMLInputElement).setSelectionRange(1, 1);
// when we try to edit an input, we insert a second value and after, based on cursor position, we change the value
// we must use userEvent because the keyboard event must trigger also the change event (fireEvent doesn't do that)
await user.keyboard('4');

act(() => (codeInputs[3] as HTMLInputElement).focus());
await waitFor(() => {
expect(codeInputs[3]).toHaveFocus();
});
await waitFor(() => {
expect(codeInputs[2]).toHaveValue('4');
});
// move the cursor at the start of the input and try to edit again
act(() => (codeInputs[2] as HTMLInputElement).focus());
(codeInputs[2] as HTMLInputElement).setSelectionRange(0, 0);
// try to edit again
await user.keyboard('3');

act(() => (codeInputs[3] as HTMLInputElement).focus());
await waitFor(() => {
expect(codeInputs[3]).toHaveFocus();
});
await waitFor(() => {
expect(codeInputs[2]).toHaveValue('3');
});
// delete the value
act(() => (codeInputs[2] as HTMLInputElement).focus());
await user.keyboard('{Backspace}');
await waitFor(() => {
expect(codeInputs[2]).toHaveValue('');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ describe('CodeModal Component', () => {
const button = within(dialog).getByTestId('codeCancelButton');
fireEvent.click(button);
await waitFor(() => {
expect(cancelButtonMock).toBeCalledTimes(1);
expect(cancelButtonMock).toHaveBeenCalledTimes(1);
});
});

Expand All @@ -132,8 +132,8 @@ describe('CodeModal Component', () => {
expect(button).toBeEnabled();
});
fireEvent.click(button);
expect(confirmButtonMock).toBeCalledTimes(1);
expect(confirmButtonMock).toBeCalledWith(['0', '1', '2', '3', '4']);
expect(confirmButtonMock).toHaveBeenCalledTimes(1);
expect(confirmButtonMock).toHaveBeenCalledWith(['0', '1', '2', '3', '4']);
});

it('shows error', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,5 +198,8 @@
"title": "Vuoi davvero uscire da SEND?",
"body": "La disconnessione è in corso. Se hai cambiato idea premi “Mantieni l’accesso” entro pochi secondi.",
"action": "Mantieni l’accesso"
},
"code-modal": {
"digits": ["prima cifra", "seconda cifra", "terza cifra", "quarta cifra", "ultima cifra"]
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Trans, useTranslation } from 'react-i18next';

import { Box, Typography } from '@mui/material';
import { AppResponse, AppResponsePublisher, CodeModal, ErrorMessage } from '@pagopa-pn/pn-commons';
import { ButtonNaked } from '@pagopa/mui-italia';

import { AddressType, ChannelType } from '../../models/contacts';

Expand Down Expand Up @@ -78,15 +79,19 @@ const ContactCodeDialog: React.FC<Props> = ({
i18nKey={`${labelRoot}.${contactType}-new-code`}
ns="recapiti"
components={[
<Typography
<ButtonNaked
key="newCodeBtn"
role="button"
tabIndex={0}
variant="body2"
size="medium"
onClick={() => onConfirm()}
color="primary"
sx={{ textDecoration: 'underline', display: 'inline', cursor: 'pointer' }}
sx={{
textDecoration: 'underline',
display: 'inline',
fontWeight: 400,
verticalAlign: 'baseline',
}}
data-testid="newCodeBtn"
component={Typography}
/>,
]}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,5 +211,8 @@
"title": "Vuoi davvero uscire da SEND?",
"body": "La disconnessione è in corso. Se hai cambiato idea premi “Mantieni l’accesso” entro pochi secondi.",
"action": "Mantieni l’accesso"
},
"code-modal": {
"digits": ["prima cifra", "seconda cifra", "terza cifra", "quarta cifra", "ultima cifra"]
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Trans, useTranslation } from 'react-i18next';

import { Box, Typography } from '@mui/material';
import { AppResponse, AppResponsePublisher, CodeModal, ErrorMessage } from '@pagopa-pn/pn-commons';
import { ButtonNaked } from '@pagopa/mui-italia';

import { AddressType, ChannelType } from '../../models/contacts';

Expand All @@ -25,8 +26,9 @@ const ContactCodeDialog: React.FC<Props> = ({
}) => {
const { t } = useTranslation(['common', 'recapiti']);
const contactType = channelType.toLowerCase();
const codeModalRef =
useRef<{ updateError: (error: ErrorMessage, codeNotValid: boolean) => void }>(null);
const codeModalRef = useRef<{
updateError: (error: ErrorMessage, codeNotValid: boolean) => void;
}>(null);
const labelRoot = `${addressType.toLowerCase()}-contacts`;

const handleAddressUpdateError = useCallback(
Expand Down Expand Up @@ -74,13 +76,19 @@ const ContactCodeDialog: React.FC<Props> = ({
i18nKey={`${labelRoot}.${contactType}-new-code`}
ns="recapiti"
components={[
<Typography
<ButtonNaked
key="newCodeBtn"
variant="body2"
size="medium"
onClick={() => onConfirm()}
color="primary"
sx={{ textDecoration: 'underline', display: 'inline', cursor: 'pointer' }}
sx={{
textDecoration: 'underline',
display: 'inline',
fontWeight: 400,
verticalAlign: 'baseline',
}}
data-testid="newCodeBtn"
component={Typography}
/>,
]}
/>
Expand Down

0 comments on commit 4ffa18b

Please sign in to comment.