From 9586866e925b13b390b70d8227f87902a099093a Mon Sep 17 00:00:00 2001 From: Clement DEJOIE Date: Wed, 31 Jan 2024 11:34:11 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20DateSelector=20-=20Change=20=20onUp?= =?UTF-8?q?datedDate=20argument=20type=20to=20take=20into=20account=20when?= =?UTF-8?q?=20date=20will=20be=20invalid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/DateSelector.test.tsx | 22 ++++++++++++++++++- src/components/dateSelector/DateSelector.tsx | 11 ++++++++-- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/__tests__/components/DateSelector.test.tsx b/src/__tests__/components/DateSelector.test.tsx index 992b5729..252b1cff 100644 --- a/src/__tests__/components/DateSelector.test.tsx +++ b/src/__tests__/components/DateSelector.test.tsx @@ -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; let tree: ReturnType; beforeEach(() => { + mockOnChange = jest.fn(); tree = render( { 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( void; + onUpdatedDate: (date: Date | RangeError) => void; }>; interface FieldsValues { @@ -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(