:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import '@testing-library/jest-dom'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { LemonInputSelect } from './LemonInputSelect'
describe('LemonInputSelect', () => {
// Helper functions
const openDropdown = async (container: HTMLElement): Promise<HTMLInputElement> => {
const input = container.querySelector('input[type="text"]')
expect(input).toBeInTheDocument()
await userEvent.click(input!)
return input as HTMLInputElement
}
const findDropdownButtonByText = async (text: string): Promise<HTMLElement | undefined> => {
const dropdownButtons = await screen.findAllByRole('button')
return dropdownButtons.find((button) => button.textContent?.includes(text))
}
it('disables the input and explains why when disabledReason is set', async () => {
render(
<LemonInputSelect
mode="multiple"
options={[]}
value={[]}
onChange={jest.fn()}
placeholder="Select values"
disabledReason="You don't have access to edit this field"
/>
)
const input = screen.getByPlaceholderText('Select values')
expect(input).toBeDisabled()
await userEvent.hover(input.closest('.LemonInput') as HTMLElement)
expect(await screen.findByText("You don't have access to edit this field")).toBeInTheDocument()
})
it('does not allow removing selected values when disabledReason is set', () => {
const onChange = jest.fn()
const { container } = render(
<LemonInputSelect
mode="multiple"
options={[{ key: 'option-a', label: 'Option A' }]}
value={['option-a']}
onChange={onChange}
disabledReason="You don't have access to edit this field"
/>
)
// The selected value still shows, but its remove (x) button must not render
expect(screen.getByText('Option A')).toBeInTheDocument()
expect(container.querySelector('.LemonSnack__close')).toBeNull()
expect(onChange).not.toHaveBeenCalled()
})
it('renders selected string values with indexed option lookups', () => {
let reads = 0
const options = Array.from({ length: 100 }, (_, index) => ({
get key(): string {
reads++
return 'option-' + index
},
label: 'Option ' + index,
}))
render(
<LemonInputSelect
mode="multiple"
options={options}
value={Array.from({ length: 100 }, (_, index) => 'option-' + index)}
onChange={jest.fn()}
/>
)
expect(screen.getByText('Option 99')).toBeInTheDocument()
expect(reads).toBeLessThan(options.length * 15)
})
it('works with boolean values', () => {
const onChange = jest.fn()
render(
<LemonInputSelect<boolean>
mode="multiple"
options={[
{ key: 'boolean-true', label: 'True', value: true },
{ key: 'boolean-false', label: 'False', value: false },
]}
value={[true]}
onChange={onChange}
/>
)
// Verify the selected boolean option is displayed with correct label
expect(screen.getByText('True')).toBeInTheDocument()
})
it('works with mixed boolean and string values', () => {
const onChange = jest.fn()
render(
<LemonInputSelect<boolean | string>
mode="multiple"
options={[
{ key: 'boolean-true-option', label: 'Boolean True', value: true },
{ key: 'boolean-false-option', label: 'Boolean False', value: false },
{ key: 'string-true-option', label: 'String True', value: 'true' },
{ key: 'variant-option', label: 'Variant', value: 'some-variant' },
]}
value={[true, 'some-variant']}
onChange={onChange}
/>
)
// Verify both typed values are displayed with correct labels
expect(screen.getByText('Boolean True')).toBeInTheDocument()
expect(screen.getByText('Variant')).toBeInTheDocument()
})
it('displays correct labels for typed values', () => {
const onChange = jest.fn()
render(
<LemonInputSelect<boolean | string>
mode="multiple"
options={[
{ key: 'boolean-true-option', label: 'Boolean True', value: true },
{ key: 'string-variant-option', label: 'String Variant', value: 'some-variant' },
]}
value={[true, 'some-variant']}
onChange={onChange}
/>
)
// Verify that typed values display their proper labels
expect(screen.getAllByText('Boolean True').length).toBeGreaterThanOrEqual(1)
expect(screen.getAllByText('String Variant').length).toBeGreaterThanOrEqual(1)
})
it('preserves correct types during onChange callback', () => {
// This test focuses on the onChange callback behavior
const onChange = jest.fn()
// Create a test component to manually trigger onChange
const TestComponent = (): JSX.Element => {
const handleSelect = (): void => {
// Simulate selecting a boolean option
onChange([true])
}
const handleSelectString = (): void => {
// Simulate selecting a string option
onChange(['string-value'])
}
const handleSelectNumber = (): void => {
// Simulate selecting a number option
onChange([42])
}
return (
<div>
<button onClick={handleSelect}>Select Boolean</button>
<button onClick={handleSelectString}>Select String</button>
<button onClick={handleSelectNumber}>Select Number</button>
</div>
)
}
render(<TestComponent />)
// Test boolean type preservation
const booleanButton = screen.getByText('Select Boolean')
booleanButton.click()
expect(onChange).toHaveBeenCalledWith([true])
let lastCall = onChange.mock.calls[onChange.mock.calls.length - 1][0]
expect(typeof lastCall[0]).toBe('boolean')
expect(lastCall[0]).toBe(true)
// Test string type preservation
const stringButton = screen.getByText('Select String')
stringButton.click()
expect(onChange).toHaveBeenCalledWith(['string-value'])
lastCall = onChange.mock.calls[onChange.mock.calls.length - 1][0]
expect(typeof lastCall[0]).toBe('string')
expect(lastCall[0]).toBe('string-value')
// Test number type preservation
const numberButton = screen.getByText('Select Number')
numberButton.click()
expect(onChange).toHaveBeenCalledWith([42])
lastCall = onChange.mock.calls[onChange.mock.calls.length - 1][0]
expect(typeof lastCall[0]).toBe('number')
expect(lastCall[0]).toBe(42)
})
it.each([
['with no search text', ''],
['after editing the search down to a prefix of it', '{backspace}{backspace}'],
])('single-select mode: clicking already-selected value keeps it selected %s', async (_, keystrokes) => {
const onChange = jest.fn()
const { container } = render(
<LemonInputSelect<string>
mode="single"
options={[
{ key: 'option-1', label: 'Option 1' },
{ key: 'option-2', label: 'Option 2' },
]}
value={['option-1']}
onChange={onChange}
allowCustomValues
data-attr="test-select"
/>
)
// Verify the selected option is displayed
expect(screen.getAllByText('Option 1').length).toBeGreaterThan(0)
const input = await openDropdown(container)
if (keystrokes) {
await userEvent.type(input, keystrokes)
expect(input).toHaveValue('option')
}
const selectedOptionButton = await waitFor(async () => {
const button = await findDropdownButtonByText('Option 1')
expect(button).toBeInTheDocument()
return button
})
// A browser returns focus to the input after the option's mousedown, but jsdom does not. Clicking
// with the input still focused reproduces the blur that the selection itself causes.
expect(input).toHaveFocus()
fireEvent.click(selectedOptionButton!)
// Neither an empty selection nor the typed search text may replace the selected value
expect(onChange).not.toHaveBeenCalled()
})
it('single-select mode: custom values show with formatCreateLabel when re-opening dropdown', async () => {
const onChange = jest.fn()
const { container } = render(
<LemonInputSelect<string>
mode="single"
options={[{ key: 'existing-option', label: 'Existing Option' }]}
value={['custom-value']}
onChange={onChange}
allowCustomValues
formatCreateLabel={(input) => `${input} (new entry)`}
data-attr="test-custom-select"
/>
)
// Custom value should be displayed
expect(screen.getAllByText('custom-value').length).toBeGreaterThan(0)
await openDropdown(container)
// Wait for dropdown to appear and check for formatted label
const formattedLabel = await screen.findByText('custom-value (new entry)')
expect(formattedLabel).toBeInTheDocument()
// Click on the custom value option
const customValueButton = formattedLabel.closest('button')
expect(customValueButton).toBeInTheDocument()
await userEvent.click(customValueButton!)
// Verify selection was NOT reset (onChange not called with empty array)
expect(onChange).not.toHaveBeenCalledWith([])
})
it('single-select mode: select all + backspace clears the selection', async () => {
const onChange = jest.fn()
const { container } = render(
<LemonInputSelect<string>
mode="single"
options={[
{ key: 'option-1', label: 'Option 1' },
{ key: 'option-2', label: 'Option 2' },
]}
value={['option-1']}
onChange={onChange}
allowCustomValues
/>
)
// Verify the selected option is displayed
expect(screen.getAllByText('Option 1').length).toBeGreaterThan(0)
const input = await openDropdown(container)
// In single mode, focusing the input enters edit mode with the value selected
// Simulate selecting all text (e.g., via Cmd+A)
input.setSelectionRange(0, input.value.length)
// Press Backspace with all text selected
await userEvent.keyboard('{Backspace}')
// Verify onChange was called with empty array (clearing the selection)
expect(onChange).toHaveBeenCalledWith([])
})
it('single-select mode: focusing with a selected option still shows every option', async () => {
// Regression: for option-backed single selects the option key is an opaque id (e.g. a UUID).
// Focusing must not seed the input with that key, which would filter the dropdown down to the
// selected option alone and hide every other choice (the OAuth organization picker symptom).
const onChange = jest.fn()
const { container } = render(
<LemonInputSelect<string>
mode="single"
options={[
{ key: '019cd764-55e6-0000-67dc-7f9cb756d36e', label: 'Testbench' },
{ key: '4dc8564d-bd82-1065-2f40-97f7c50f67cf', label: 'PostHog Inc.' },
]}
value={['019cd764-55e6-0000-67dc-7f9cb756d36e']}
onChange={onChange}
/>
)
await openDropdown(container)
// Both the selected org and the other org must be selectable from the open dropdown.
expect(await findDropdownButtonByText('Testbench')).toBeInTheDocument()
expect(await findDropdownButtonByText('PostHog Inc.')).toBeInTheDocument()
})
it('custom values: typing prefix of existing option shows both entries, completing shows only one', async () => {
const onChange = jest.fn()
const { container } = render(
<LemonInputSelect<string>
mode="single"
options={[
{ key: 'test-option', label: 'Test Option' },
{ key: 'example', label: 'Example Option' },
]}
value={[]}
onChange={onChange}
allowCustomValues
formatCreateLabel={(input) => `Add "${input}"`}
/>
)
const input = await openDropdown(container)
// Type a prefix "test-opt" (partial match for "test-option")
await userEvent.type(input, 'test-opt')
// Should show 2 entries: the custom "Add 'test-opt'" and the matching "Test Option"
const addButton = await findDropdownButtonByText('Add "test-opt"')
const testButton = await findDropdownButtonByText('Test Option')
expect(addButton).toBeInTheDocument()
expect(testButton).toBeInTheDocument()
// Now complete typing to "test-option" (exact match)
await userEvent.type(input, 'ion')
// Should now show only 1 entry: the existing "Test Option"
// The custom "Add 'test-option'" should NOT appear since it matches an existing option
const dropdownButtons = await screen.findAllByRole('button')
const testButtons = dropdownButtons.filter((button) => button.textContent?.includes('Test Option'))
const addTestButtons = dropdownButtons.filter((button) => button.textContent?.includes('Add "test-option"'))
expect(testButtons.length).toBeGreaterThanOrEqual(1)
expect(addTestButtons.length).toBe(0)
})
it('multiple-select mode: selecting an option freezes the displayed results until user types again', async () => {
const onChange = jest.fn()
const { container } = render(
<LemonInputSelect<string>
mode="multiple"
options={[
{ key: 'apple', label: 'Apple' },
{ key: 'apricot', label: 'Apricot' },
{ key: 'zucchini', label: 'Zucchini' },
]}
value={[]}
onChange={onChange}
/>
)
const input = await openDropdown(container)
// Type to filter — "app" should match Apple and Apricot but not Zucchini
await userEvent.type(input, 'app')
const appleButton = await findDropdownButtonByText('Apple')
expect(appleButton).toBeInTheDocument()
expect(screen.queryByText('Zucchini')).not.toBeInTheDocument()
// Select "Apple" — input clears but results should stay frozen
await userEvent.click(appleButton!)
expect(input.value).toBe('')
// Zucchini should still not appear — the frozen filtered results persist
expect(screen.queryByText('Zucchini')).not.toBeInTheDocument()
})
it('multiple-select mode: clicking option matching search text does not toggle it off', async () => {
const onChange = jest.fn()
const { container } = render(
<LemonInputSelect<string>
mode="multiple"
options={[
{ key: '[email protected]', label: '[email protected]' },
{ key: '[email protected]', label: '[email protected]' },
]}
value={[]}
onChange={onChange}
allowCustomValues
/>
)
const input = await openDropdown(container)
// Type a value that exactly matches an option
await userEvent.type(input, '[email protected]')
// Click the matching option in the dropdown
const optionButton = await findDropdownButtonByText('[email protected]')
expect(optionButton).toBeInTheDocument()
await userEvent.click(optionButton!)
// The final onChange call should ADD the value, not remove it
const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1]
expect(lastCall[0]).toContain('[email protected]')
})
it.each([
{
name: 'commits it unchanged when the text was not touched',
typed: '',
expected: ['Acme Corp '],
},
{
name: 'trims what the person typed over it',
typed: ' Other Corp ',
expected: ['Other Corp'],
},
])('multiple-select mode: editing a value snack $name', async ({ typed, expected }) => {
const onChange = jest.fn()
const { container } = render(
<LemonInputSelect<string>
mode="multiple"
options={[{ key: 'Acme Corp ', label: 'Acme Corp ' }]}
value={['Acme Corp ']}
onChange={onChange}
allowCustomValues
/>
)
// Clicking the snack's text opens it for editing, seeding the input with its value
await userEvent.click(container.querySelector('[title="Acme Corp "]')!)
const input = container.querySelector('input[type="text"]') as HTMLInputElement
expect(input.value).toBe('Acme Corp ')
if (typed) {
await userEvent.clear(input)
await userEvent.type(input, typed)
}
await userEvent.click(document.body)
expect(onChange).toHaveBeenLastCalledWith(expected)
})
it.each([
{
name: 'adds nothing when the limit is reached',
keys: '{ArrowDown}{ArrowDown}{Enter}',
expectedSelections: [],
},
{
name: 'still removes a selected value when the limit is reached',
keys: '{Enter}',
expectedSelections: [['apricot']],
},
])('multiple-select mode: pressing Enter $name', async ({ keys, expectedSelections }) => {
const onChange = jest.fn()
const { container } = render(
<LemonInputSelect<string>
mode="multiple"
options={[
{ key: 'apple', label: 'Apple' },
{ key: 'apricot', label: 'Apricot' },
{ key: 'zucchini', label: 'Zucchini' },
]}
value={['apple', 'apricot']}
onChange={onChange}
limit={2}
/>
)
await openDropdown(container)
await userEvent.keyboard(keys)
expect(onChange.mock.calls.map((call) => call[0])).toEqual(expectedSelections)
})
it.each(['single', 'multiple'] as const)(
'%s-select mode: pressing Enter on a typed option key picks it when filtering is disabled',
async (mode) => {
const onChange = jest.fn()
const { container } = render(
<LemonInputSelect<string>
mode={mode}
options={[
{ key: 'anon-id', label: 'anon-id' },
{ key: 'user-id', label: 'user-id' },
]}
value={[]}
onChange={onChange}
allowCustomValues
disableFiltering
/>
)
const input = await openDropdown(container)
await userEvent.type(input, 'user-id{Enter}')
expect(onChange).toHaveBeenLastCalledWith(['user-id'])
}
)
})