Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix not selectable last year #1848

Merged
merged 10 commits into from
Jun 2, 2020
10 changes: 9 additions & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,15 @@
"request": "launch",
"name": "Jest Current File",
"program": "${workspaceFolder}/lib/node_modules/.bin/jest",
"args": ["--config", "${workspaceFolder}/lib/jest.config.js", "${fileBasenameNoExtension}"],
"args": [
"--runInBand",
"--config",
"${workspaceFolder}/lib/jest.config.js",
"${fileBasenameNoExtension}"
],
"sourceMaps": true,
"preLaunchTask": "npm: test:typescript - lib",
"outFiles": [ "${workspaceFolder}/lib/src/__tests__/dist/**/*.js"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,
Expand Down
13 changes: 13 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "test:typescript",
"path": "lib/",
"problemMatcher": [],
"label": "npm: test:typescript - lib",
"detail": "rimraf src/__tests__/dist && tsc -p src/__tests__/tsconfig.json"
}
]
}
3 changes: 2 additions & 1 deletion lib/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
const path = require('path');

module.exports = {
setupFilesAfterEnv: ['<rootDir>/src/__tests__/setup.js'],
setupFilesAfterEnv: ['<rootDir>/src/__tests__/setup.ts'],
testRegex: './src/__tests__/.*\\.test\\.(js|tsx|ts)$',
testURL: 'http://localhost/',
collectCoverage: true,
transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
},
modulePathIgnorePatterns: ["<rootDir>/src/__tests__/dist/"],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
coveragePathIgnorePatterns: ['<rootDir>/src/__tests__/'],
globals: {
Expand Down
3 changes: 2 additions & 1 deletion lib/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
},
"scripts": {
"test": "jest",
"test:typescript": "tsc -p src/__tests__/tsconfig.json",
"test:typescript": "rimraf src/__tests__/dist && tsc -p src/__tests__/tsconfig.json",
"test:date-fns": "UTILS=date-fns yarn test",
"test:luxon": "UTILS=luxon yarn test",
"test:moment": "UTILS=moment yarn test",
Expand Down Expand Up @@ -87,6 +87,7 @@
"@rollup/plugin-babel": "^5.0.2",
"@rollup/plugin-commonjs": "^12.0.0",
"@rollup/plugin-node-resolve": "^8.0.0",
"@testing-library/jest-dom": "^5.9.0",
"@types/enzyme": "^3.10.5",
"@types/enzyme-adapter-react-16": "^1.0.3",
"@types/fs-extra": "^8.1.0",
Expand Down
1 change: 1 addition & 0 deletions lib/src/__tests__/DatePicker.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -248,3 +248,4 @@ it('Should not add to loading queue when synchronous', () => {
'Enter Date'
);
});

24 changes: 24 additions & 0 deletions lib/src/__tests__/DatePickerTestingLib.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import * as React from 'react';
import { DatePicker } from '../DatePicker';
import { TextField } from '@material-ui/core';
import { screen } from '@testing-library/react';
import { createClientRender } from './createClientRender';

describe('<DatePicker />', () => {
const render = createClientRender({ strict: false });
it('Allows to select edge years from list', () => {
Comment on lines +8 to +9
Copy link
Member

@oliviertassinari oliviertassinari Jun 1, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const render = createClientRender({ strict: false });
it('Allows to select edge years from list', () => {
// StrictModeViolation: uses Grow
const render = createClientRender({ strict: false });
it('Should disable the year on the edge if it doesn`t fit to the current date', () => {

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh my gosh, just realize that this test will fail each year on January 1st. I hate writing tests for datepickers XD

render(
<DatePicker
open
value={null}
onChange={jest.fn()}
views={['year']}
minDate={new Date('2000-01-01')}
maxDate={new Date('2010-01-01')}
renderInput={props => <TextField {...props} />}
/>
);

expect(screen.getByRole('button', { name: '2010' })).toBeDisabled();
});
});
3 changes: 1 addition & 2 deletions lib/src/__tests__/DateTimePickerTestingLib.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { DesktopDateTimePicker } from '../DateTimePicker';
import { createClientRender } from './createClientRender';
import { fireEvent, screen } from '@testing-library/react';

describe('DateTimePicker testing lib', () => {
describe('<DateTimePicker />', () => {
const render = createClientRender({ strict: false });

it('prop: mask – should take the mask prop into account', () => {
Expand Down Expand Up @@ -46,7 +46,6 @@ describe('DateTimePicker testing lib', () => {
});

it('prop: minDateTime – hours is disabled by date part', () => {
screen.debug();
render(
<DesktopDateTimePicker
open
Expand Down
6 changes: 4 additions & 2 deletions lib/src/__tests__/setup.js → lib/src/__tests__/setup.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import '@testing-library/jest-dom';

const Enzyme = require('enzyme');
const EnzymeAdapter = require('enzyme-adapter-react-16');

Expand All @@ -18,8 +20,8 @@ document.createRange = () => ({

// Convert any console error into a thrown error
const error = console.error;
console.error = (...args) => {
error.apply(console, args);
console.error = (...args: any[]) => {
error.apply(console, args as any);
if (args[0] instanceof Error) {
throw args[0];
} else {
Expand Down
69 changes: 58 additions & 11 deletions lib/src/__tests__/test-utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,38 @@ import { IUtils } from '@date-io/core/IUtils';
import { DatePickerProps } from '../DatePicker';
import { MaterialUiPickersDate } from '../typings/date';
import { BasePickerProps } from '../typings/BasePicker';
import { createClientRender } from './createClientRender';
import { queryHelpers, Matcher, MatcherOptions } from '@testing-library/react/pure';

export const queryByMuiTest = queryHelpers.queryByAttribute.bind(null, 'data-mui-test');
export const queryAllByMuiTest = queryHelpers.queryAllByAttribute.bind(null, 'data-mui-test');

export function getAllByMuiTest(
id: Matcher,
container: HTMLElement = document.body,
options?: MatcherOptions
): Element[] {
const els = queryAllByMuiTest(container, id, options);
if (!els.length) {
throw queryHelpers.getElementError(
`Unable to find an element by: [data-mui-test="${id}"]`,
container
);
}
return els;
}

export function getByMuiTest(...args: Parameters<typeof getAllByMuiTest>): Element {
const result = getAllByMuiTest(...args);
if (result.length > 0) {
return result[0];
}

throw queryHelpers.getElementError(
`Unable to find an element by: [data-mui-test="${args[0]}"]`,
document.body
);
}

interface WithUtilsProps {
utils: IUtils<MaterialUiPickersDate>;
Expand Down Expand Up @@ -39,25 +71,40 @@ export const shallow = <P extends WithUtilsProps>(element: React.ReactElement<P>
export const mount = <P extends WithUtilsProps>(element: React.ReactElement<P>) =>
enzyme.mount(<LocalizationProvider dateAdapter={UtilClassToUse}>{element}</LocalizationProvider>);

export function mountPickerWithState<TValue>(
defaultValue: TValue,
render: (
props: Pick<BasePickerProps<TValue, TValue>, 'onChange' | 'value'> & {
renderInput: DatePickerProps['renderInput'];
}
) => React.ReactElement
) {
const PickerMountComponent = () => {
type RenderPicker<TValue> = (
props: Pick<BasePickerProps<TValue, TValue>, 'onChange' | 'value'> & {
renderInput: DatePickerProps['renderInput'];
}
) => React.ReactElement;

function createPickerWithState<TValue>(defaultValue: TValue, renderFn: RenderPicker<TValue>) {
const PickerWithState = () => {
const [value, setDate] = React.useState(defaultValue);

return render({
return renderFn({
value,
onChange: date => setDate(date),
renderInput: props => <TextField {...props} />,
});
};

return mount(<PickerMountComponent />);
return <PickerWithState />;
}

export function mountPickerWithState<TValue>(
defaultValue: TValue,
renderPicker: RenderPicker<TValue>
) {
return mount(createPickerWithState(defaultValue, renderPicker));
}

export function renderPickerWithState<TValue>(
defaultValue: TValue,
renderPicker: RenderPicker<TValue>,
clientRenderOptions?: { strict?: boolean }
) {
const render = createClientRender(clientRenderOptions);
return render(createPickerWithState(defaultValue, renderPicker));
}

export const shallowRender = (render: (props: any) => React.ReactElement<any>) => {
Expand Down
5 changes: 4 additions & 1 deletion lib/src/__tests__/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
"exclude": [],
"include": ["../../typings.d.ts", "./typings.d.ts", "./**/*.tsx", "./**/*.ts", "./typescript/*"],
"compilerOptions": {
// "baseUrl": ".",
"emitDeclarationOnly": false,
"noEmit": false,
"outDir": "./dist",
"sourceMap": true
}
}
26 changes: 13 additions & 13 deletions lib/src/views/Calendar/YearSelection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,11 @@ export const useStyles = makeStyles(
);

export const YearSelection: React.FC<YearSelectionProps> = ({
date,
date: __dateOrNull,
onChange,
onYearChange,
minDate,
maxDate,
disablePast,
disableFuture,
isDateDisabled,
shouldDisableYear,
changeFocusedDay,
Expand All @@ -60,7 +58,9 @@ export const YearSelection: React.FC<YearSelectionProps> = ({
const theme = useTheme();
const utils = useUtils();
const classes = useStyles();
const currentYear = utils.getYear(date);

const selectedDate = __dateOrNull || now;
const currentYear = utils.getYear(selectedDate);
const wrapperVariant = React.useContext(WrapperVariantContext);
const selectedYearRef = React.useRef<HTMLButtonElement>(null);
const [focusedYear, setFocusedYear] = React.useState<number | null>(currentYear);
Expand All @@ -80,7 +80,7 @@ export const YearSelection: React.FC<YearSelectionProps> = ({

const handleYearSelection = React.useCallback(
(year: number, isFinish = true) => {
const newDate = utils.setYear(date || now, year);
const newDate = utils.setYear(selectedDate, year);
if (isDateDisabled(newDate)) {
return;
}
Expand All @@ -92,16 +92,16 @@ export const YearSelection: React.FC<YearSelectionProps> = ({
onChange(newDate, isFinish);
changeFocusedDay(newDate);
},
[changeFocusedDay, date, isDateDisabled, now, onChange, onYearChange, utils]
[changeFocusedDay, selectedDate, isDateDisabled, onChange, onYearChange, utils]
);

const focusYear = React.useCallback(
(year: number) => {
if (!isDateDisabled(utils.setYear(date, year))) {
if (!isDateDisabled(utils.setYear(selectedDate, year))) {
setFocusedYear(year);
}
},
[date, isDateDisabled, utils]
[selectedDate, isDateDisabled, utils]
);

const yearsInRow = wrapperVariant === 'desktop' ? 4 : 3;
Expand Down Expand Up @@ -129,11 +129,11 @@ export const YearSelection: React.FC<YearSelectionProps> = ({
allowKeyboardControl={allowKeyboardControl}
focused={yearNumber === focusedYear}
ref={selected ? selectedYearRef : undefined}
disabled={Boolean(
(disablePast && utils.isBeforeYear(year, now)) ||
(disableFuture && utils.isAfterYear(year, now)) ||
(shouldDisableYear && shouldDisableYear(year))
)}
disabled={
// Make sure that final date (with month and day included) will be enabled
isDateDisabled(utils.setYear(selectedDate, yearNumber)) ||
(shouldDisableYear && shouldDisableYear(year))
}
>
{utils.format(year, 'year')}
</Year>
Expand Down
Loading