diff --git a/src/containers/contextContainer.js b/src/containers/contextContainer.js index 96618582..c35f40e7 100644 --- a/src/containers/contextContainer.js +++ b/src/containers/contextContainer.js @@ -1,29 +1,13 @@ -import {head, pick} from 'lodash'; +import {pick} from 'lodash'; import React from 'react'; import {polyfill} from 'react-lifecycles-compat'; import TypeaheadContext from '../TypeaheadContext'; -import {getHintText} from '../utils'; +import {getHintText, getIsOnlyResult} from '../utils'; import {RETURN} from '../constants'; function contextContainer(Typeahead) { class WrappedTypeahead extends React.Component { - state = { - isOnlyResult: false, - }; - - static getDerivedStateFromProps(props, state) { - const {allowNew, highlightOnlyResult, results} = props; - - if (!highlightOnlyResult || allowNew) { - return null; - } - - return { - isOnlyResult: results.length === 1 && !head(results).disabled, - }; - } - componentDidUpdate(prevProps, prevState) { const {allowNew, onInitialItemChange, results} = this.props; @@ -49,7 +33,7 @@ function contextContainer(Typeahead) { value={{ ...contextValues, hintText: getHintText(this.props), - isOnlyResult: this.state.isOnlyResult, + isOnlyResult: getIsOnlyResult(this.props), }}> { + let props; + + beforeEach(() => { + props = { + allowNew: false, + highlightOnlyResult: true, + results: ['The only result!'], + }; + }); + + it('returns true', () => { + expect(getIsOnlyResult(props)).to.equal(true); + }); + + it('returns false when `highlightOnlyResult` is disabled', () => { + props.highlightOnlyResult = false; + expect(getIsOnlyResult(props)).to.equal(false); + }); + + it('returns false when custom options are allowed', () => { + props.allowNew = true; + expect(getIsOnlyResult(props)).to.equal(false); + }); + + it('returns false when there are more or less than one result', () => { + props.results = ['One', 'Two']; + expect(getIsOnlyResult(props)).to.equal(false); + + props.results = []; + expect(getIsOnlyResult(props)).to.equal(false); + }); + + it('returns false when the only result is disabled', () => { + props.results = [{disabled: true}]; + expect(getIsOnlyResult(props)).to.equal(false); + }); +});