Skip to content

Commit

Permalink
Merge pull request #179 from ZeroGachis/task/sdet-223-add-error-on-in…
Browse files Browse the repository at this point in the history
…valid-date

✨ DateSelector - Change  onUpdatedDate argument type to take into acc…
  • Loading branch information
clementdejoie authored Jan 31, 2024
2 parents fdac469 + 9586866 commit 996eaa2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
22 changes: 21 additions & 1 deletion src/__tests__/components/DateSelector.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import { DeviceEventEmitter } from 'react-native';
import { render, userEvent, screen, act } from '../../shared/testUtils';

const mockedTestID = 'mockedTestID';
const mockOnChange = jest.fn();
let mockOnChange: jest.Mock<unknown, unknown[], unknown>;
let tree: ReturnType<typeof render>;

beforeEach(() => {
mockOnChange = jest.fn();
tree = render(
<DateSelector
prefilled={new Date(2003, 1, 1)}
Expand Down Expand Up @@ -69,6 +70,25 @@ describe('MODULE | DateField', () => {
expect(yearField.props.value).toBe('06');
});

it('should not cast invalid date into a valid one', async () => {
const user = userEvent.setup();

const dayField = screen.getByTestId(mockedTestID + '/day');
await user.type(dayField, '33');

const monthField = screen.getByTestId(mockedTestID + '/month');
await user.type(monthField, '5');

const yearField = screen.getByTestId(mockedTestID + '/year');
await user.type(yearField, '6');

await act(() => {
DeviceEventEmitter.emit('keyboardDidHide', {});
});

expect(mockOnChange).toHaveBeenCalledWith(expect.any(RangeError));
});

it('should display an error message', async () => {
tree.rerender(
<DateSelector
Expand Down
11 changes: 9 additions & 2 deletions src/components/dateSelector/DateSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
type DateSelectorProps = WithTestID<{
prefilled: Date;
errorMessage?: string;
onUpdatedDate: (date: Date) => void;
onUpdatedDate: (date: Date | RangeError) => void;
}>;

interface FieldsValues {
Expand Down Expand Up @@ -169,7 +169,14 @@ function fromFieldsToDate(fieldsValues: FieldsValues) {
parseInt(fieldsValues.monthField),
2000 + parseInt(fieldsValues.yearField),
];
return new Date(year, month - 1, day);

const date = new Date(`${year}-${month}-${day}`);

if (isNaN(date.getTime())) {
return RangeError("Invalid date");
}

return date;
}

function filledFieldsValues(
Expand Down

0 comments on commit 996eaa2

Please sign in to comment.