diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js index 09f17e9d5513d7..b463d22b2b8162 100644 --- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js +++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js @@ -2,6 +2,7 @@ import React from 'react'; import { expect } from 'chai'; import { createMount, getClasses } from '@material-ui/core/test-utils'; import describeConformance from '@material-ui/core/test-utils/describeConformance'; +import consoleErrorMock from 'test/utils/consoleErrorMock'; import { spy } from 'sinon'; import { createClientRender, fireEvent } from 'test/utils/createClientRender'; import Autocomplete from './Autocomplete'; @@ -370,15 +371,22 @@ describe('', () => { }); }); - describe('free solo', () => { - it('should accept any value', () => { - const options = [{ name: 'test' }, { name: 'foo' }]; + describe('warnings', () => { + beforeEach(() => { + consoleErrorMock.spy(); + }); + + afterEach(() => { + consoleErrorMock.reset(); + }); + + it('warn if getOptionLabel do not return a string', () => { const handleChange = spy(); const { container } = render( option.name} renderInput={params => } />, @@ -388,6 +396,10 @@ describe('', () => { fireEvent.keyDown(input, { key: 'Enter' }); expect(handleChange.callCount).to.equal(1); expect(handleChange.args[0][1]).to.equal('a'); + expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.args()[0][0]).to.include( + 'For the input option: "a", `getOptionLabel` returns: undefined', + ); }); }); }); diff --git a/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js b/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js index fba6b3480a3eaf..72d7c84c367f72 100644 --- a/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js +++ b/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js @@ -171,10 +171,26 @@ export default function useAutocomplete(props) { let newInputValue; if (multiple) { newInputValue = ''; - } else if (freeSolo && typeof newValue === 'string') { - newInputValue = newValue; + } else if (newValue == null) { + newInputValue = ''; } else { - newInputValue = newValue != null ? getOptionLabel(newValue) : ''; + const optionLabel = getOptionLabel(newValue); + + if (process.env.NODE_ENV !== 'production') { + if (typeof optionLabel !== 'string') { + console.error( + [ + 'Material-UI: the `getOptionLabel` method of useAutocomplete do not handle the options correctly.', + `The component expect a string but received ${typeof optionLabel}.`, + `For the input option: ${JSON.stringify( + newValue, + )}, \`getOptionLabel\` returns: ${newInputValue}.`, + ].join('\n'), + ); + } + } + + newInputValue = typeof optionLabel === 'string' ? optionLabel : ''; } setInputValue(newInputValue);