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

[Select] Warn for unmatched value #17691

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/pages/api/select.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ You can learn more about the difference by [reading this guide](/guides/minimizi
| <span class="prop-name">open</span> | <span class="prop-type">bool</span> | | Control `select` open state. You can only use it when the `native` prop is `false` (default). |
| <span class="prop-name">renderValue</span> | <span class="prop-type">func</span> | | Render the selected value. You can only use it when the `native` prop is `false` (default).<br><br>**Signature:**<br>`function(value: any) => ReactElement`<br>*value:* The `value` provided to the component. |
| <span class="prop-name">SelectDisplayProps</span> | <span class="prop-type">object</span> | | Props applied to the clickable div element. |
| <span class="prop-name">value</span> | <span class="prop-type">any</span> | | The input value. This prop is required when the `native` prop is `false` (default). |
| <span class="prop-name">value</span> | <span class="prop-type">any</span> | | The input value. Providing an empty string will select no options. This prop is required when the `native` prop is `false` (default). Set to an empty string `''` if you don't want any of the available options to be selected. |
| <span class="prop-name">variant</span> | <span class="prop-type">'standard'<br>&#124;&nbsp;'outlined'<br>&#124;&nbsp;'filled'</span> | <span class="prop-default">'standard'</span> | The variant to use. |

The `ref` is forwarded to the root element.
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/components/selects/DialogSelect.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export default function DialogSelect() {
});

const handleChange = name => event => {
setState({ ...state, [name]: Number(event.target.value) });
setState({ ...state, [name]: Number(event.target.value) || '' });
};

const handleClickOpen = () => {
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/components/selects/DialogSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export default function DialogSelect() {
const handleChange = (name: keyof typeof state) => (
event: React.ChangeEvent<{ value: unknown }>,
) => {
setState({ ...state, [name]: Number(event.target.value) });
setState({ ...state, [name]: Number(event.target.value) || '' });
};

const handleClickOpen = () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/material-ui/src/InputBase/InputBase.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ describe('<InputBase />', () => {
InputProps={{
endAdornment: (
<InputAdornment position="end">
<Select value="a" name="suffix" />
<Select value="" name="suffix" />
</InputAdornment>
),
}}
Expand Down
3 changes: 2 additions & 1 deletion packages/material-ui/src/Select/Select.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,9 @@ Select.propTypes = {
*/
SelectDisplayProps: PropTypes.object,
/**
* The input value.
* The input value. Providing an empty string will select no options.
* This prop is required when the `native` prop is `false` (default).
* Set to an empty string `''` if you don't want any of the available options to be selected.
*/
value: PropTypes.any,
/**
Expand Down
45 changes: 36 additions & 9 deletions packages/material-ui/src/Select/Select.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe('<Select />', () => {
mount = createMount({ strict: false });
});

describeConformance(<Select value="none" />, () => ({
describeConformance(<Select value="" />, () => ({
classes,
inheritComponent: Input,
mount,
Expand All @@ -36,7 +36,7 @@ describe('<Select />', () => {
inputProps={{
classes: { root: 'root' },
}}
value="none"
value=""
/>,
);

Expand Down Expand Up @@ -281,6 +281,33 @@ describe('<Select />', () => {

expect(getByRole('button')).to.have.text('Twenty');
});

describe('warnings', () => {
let consoleWarnContainer = null;

beforeEach(() => {
consoleWarnContainer = console.warn;
console.warn = spy();
});

afterEach(() => {
console.warn = consoleWarnContainer;
consoleWarnContainer = null;
});

it('warns when the value is not present in any option', () => {
render(
<Select value={20}>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>,
);
expect(console.warn.callCount).to.equal(1);
expect(console.warn.args[0][0]).to.include(
'Material-UI: you have provided an out-of-range value `20` for the select component.',
);
});
});
});

describe('SVG icon', () => {
Expand Down Expand Up @@ -311,31 +338,31 @@ describe('<Select />', () => {
it('sets aria-expanded="true" when the listbox is displayed', () => {
// since we make the rest of the UI inaccessible when open this doesn't
// technically matter. This is only here in case we keep the rest accessible
const { getByRole } = render(<Select open value="none" />);
const { getByRole } = render(<Select open value="" />);

expect(getByRole('button', { hidden: true })).to.have.attribute('aria-expanded', 'true');
});

specify('aria-expanded is not present if the listbox isnt displayed', () => {
const { getByRole } = render(<Select value="none" />);
const { getByRole } = render(<Select value="" />);

expect(getByRole('button')).not.to.have.attribute('aria-expanded');
});

it('indicates that activating the button displays a listbox', () => {
const { getByRole } = render(<Select value="none" />);
const { getByRole } = render(<Select value="" />);

expect(getByRole('button')).to.have.attribute('aria-haspopup', 'listbox');
});

it('renders an element with listbox behavior', () => {
const { getByRole } = render(<Select open value="none" />);
const { getByRole } = render(<Select open value="" />);

expect(getByRole('listbox')).to.be.visible;
});

specify('the listbox is focusable', () => {
const { getByRole } = render(<Select open value="none" />);
const { getByRole } = render(<Select open value="" />);

getByRole('listbox').focus();

Expand All @@ -344,7 +371,7 @@ describe('<Select />', () => {

it('identifies each selectable element containing an option', () => {
const { getAllByRole } = render(
<Select open value="none">
<Select open value="">
<MenuItem value="1">First</MenuItem>
<MenuItem value="2">Second</MenuItem>
</Select>,
Expand Down Expand Up @@ -710,7 +737,7 @@ describe('<Select />', () => {
expect(ref.current.node).to.have.property('tagName', 'INPUT');

setProps({
value: 20,
value: '',
});
expect(ref.current.node).to.have.property('tagName', 'INPUT');
});
Expand Down
23 changes: 23 additions & 0 deletions packages/material-ui/src/Select/SelectInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ const SelectInput = React.forwardRef(function SelectInput(props, ref) {
let displaySingle;
const displayMultiple = [];
let computeDisplay = false;
let foundMatch = false;

// No need to display any value if the field is empty.
if (isFilled(props) || displayEmpty) {
Expand Down Expand Up @@ -230,6 +231,10 @@ const SelectInput = React.forwardRef(function SelectInput(props, ref) {
}
}

if (selected) {
foundMatch = true;
}

return React.cloneElement(child, {
'aria-selected': selected ? 'true' : undefined,
onClick: handleItemClick(child),
Expand All @@ -240,6 +245,24 @@ const SelectInput = React.forwardRef(function SelectInput(props, ref) {
});
});

if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
if (!foundMatch && !multiple && value !== '') {
const values = React.Children.toArray(children).map(child => child.props.value);
console.warn(
[
`Material-UI: you have provided an out-of-range value \`${value}\` for the select ${
name ? `(name="${name}") ` : ''
}component.`,
"Consider providing a value that matches one of the available options or ''.",
`The available values are ${values.join(', ') || '""'}.`,
].join('\n'),
);
}
}, [foundMatch, children, multiple, name, value]);
}

if (computeDisplay) {
display = multiple ? displayMultiple.join(', ') : displaySingle;
}
Expand Down
34 changes: 17 additions & 17 deletions packages/material-ui/src/TablePagination/TablePagination.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ describe('<TablePagination />', () => {

before(() => {
classes = getClasses(
<TablePagination count={1} onChangePage={() => {}} page={0} rowsPerPage={1} />,
<TablePagination count={1} onChangePage={() => {}} page={0} rowsPerPage={10} />,
);
// StrictModeViolation: uses #html()
mount = createMount({ strict: false });
Expand All @@ -41,7 +41,7 @@ describe('<TablePagination />', () => {
});

describeConformance(
<TablePagination count={1} onChangePage={() => {}} page={0} rowsPerPage={1} />,
<TablePagination count={1} onChangePage={() => {}} page={0} rowsPerPage={10} />,
() => ({
classes,
inheritComponent: TableCell,
Expand All @@ -57,8 +57,8 @@ describe('<TablePagination />', () => {
let labelDisplayedRowsCalled = false;
function labelDisplayedRows({ from, to, count, page }) {
labelDisplayedRowsCalled = true;
assert.strictEqual(from, 6);
assert.strictEqual(to, 10);
assert.strictEqual(from, 11);
assert.strictEqual(to, 20);
assert.strictEqual(count, 42);
assert.strictEqual(page, 1);
return `Page ${page}`;
Expand All @@ -73,7 +73,7 @@ describe('<TablePagination />', () => {
page={1}
onChangePage={noop}
onChangeRowsPerPage={noop}
rowsPerPage={5}
rowsPerPage={10}
labelDisplayedRows={labelDisplayedRows}
/>
</TableRow>
Expand All @@ -94,7 +94,7 @@ describe('<TablePagination />', () => {
page={0}
onChangePage={noop}
onChangeRowsPerPage={noop}
rowsPerPage={5}
rowsPerPage={10}
labelRowsPerPage="Zeilen pro Seite:"
/>
</TableRow>
Expand All @@ -110,11 +110,11 @@ describe('<TablePagination />', () => {
<TableFooter>
<TableRow>
<TablePagination
count={6}
count={11}
page={0}
onChangePage={noop}
onChangeRowsPerPage={noop}
rowsPerPage={5}
rowsPerPage={10}
/>
</TableRow>
</TableFooter>
Expand All @@ -133,11 +133,11 @@ describe('<TablePagination />', () => {
<TableFooter>
<TableRow>
<TablePagination
count={6}
count={11}
page={1}
onChangePage={noop}
onChangeRowsPerPage={noop}
rowsPerPage={5}
rowsPerPage={10}
/>
</TableRow>
</TableFooter>
Expand All @@ -157,13 +157,13 @@ describe('<TablePagination />', () => {
<TableFooter>
<TableRow>
<TablePagination
count={15}
count={30}
page={page}
onChangePage={(event, nextPage) => {
page = nextPage;
}}
onChangeRowsPerPage={noop}
rowsPerPage={5}
rowsPerPage={10}
/>
</TableRow>
</TableFooter>
Expand All @@ -182,13 +182,13 @@ describe('<TablePagination />', () => {
<TableFooter>
<TableRow>
<TablePagination
count={15}
count={30}
page={page}
onChangePage={(event, nextPage) => {
page = nextPage;
}}
onChangeRowsPerPage={noop}
rowsPerPage={5}
rowsPerPage={10}
/>
</TableRow>
</TableFooter>
Expand All @@ -208,7 +208,7 @@ describe('<TablePagination />', () => {
<TablePagination
count={0}
page={0}
rowsPerPage={5}
rowsPerPage={10}
onChangePage={noop}
onChangeRowsPerPage={noop}
/>
Expand Down Expand Up @@ -266,8 +266,8 @@ describe('<TablePagination />', () => {
<TableRow>
<TablePagination
page={2}
rowsPerPage={5}
count={10}
count={20}
rowsPerPage={10}
onChangePage={noop}
onChangeRowsPerPage={noop}
/>
Expand Down
6 changes: 6 additions & 0 deletions test/utils/consoleError.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ function consoleError() {
console.info(...args);
throw new Error(...args);
};

console.warn = (...args) => {
// Can't use log as karma is not displaying them.
console.info(...args);
throw new Error(...args);
Copy link
Member

@oliviertassinari oliviertassinari Oct 3, 2019

Choose a reason for hiding this comment

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

As we have started to use console.warn in the code base, I think that we should throw the tests for them. I could only find the origin of the new warning thanks to this. Turns out, the table pagination tests had unmatching values.

cc @eps1lon

};
}

module.exports = consoleError;