Skip to content

: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.

6.3 KB
Raw Blame
import { MOCK_DEFAULT_BASIC_USER, MOCK_SECOND_BASIC_USER, MOCK_USER_UUID } from 'lib/api.mock'

import '@testing-library/jest-dom'

import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Provider } from 'kea'
import { expectLogic } from 'kea-test-utils'

import { userLogic } from 'scenes/userLogic'

import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { OrganizationMemberType, UserBasicType } from '~/types'

import { MemberSelect } from './MemberSelect'

function member(id: string, user: UserBasicType, level: number): OrganizationMemberType {
    return {
        id,
        user,
        level,
        joined_at: '2020-09-24T15:05:26Z',
        updated_at: '2020-09-24T15:05:26Z',
        is_2fa_enabled: false,
        has_social_auth: false,
        last_login: null,
    }
}

describe('MemberSelect', () => {
    let onChange: jest.Mock

    beforeEach(async () => {
        useMocks({
            get: {
                '/api/organizations/:organization_id/members/': {
                    results: [member('1', MOCK_DEFAULT_BASIC_USER, 8), member('2', MOCK_SECOND_BASIC_USER, 1)],
                },
            },
        })
        initKeaTests()
        userLogic().mount()
        await expectLogic(userLogic).toMatchValues({ user: expect.objectContaining({ uuid: MOCK_USER_UUID }) })
        onChange = jest.fn()
    })

    afterEach(() => {
        cleanup()
    })

    function renderSelect(props: Partial<Parameters<typeof MemberSelect>[0]> = {}): void {
        render(
            <Provider>
                <>
                    <MemberSelect value={null} onChange={onChange} {...props} />
                    <button type="button">Outside</button>
                </>
            </Provider>
        )
    }

    it('shows the current user at the top labelled "(you)"', async () => {
        renderSelect()
        await userEvent.click(screen.getByText('Any user'))

        await waitFor(() => {
            expect(screen.getByText(MOCK_DEFAULT_BASIC_USER.first_name)).toBeInTheDocument()
            expect(screen.getByText('(you)')).toBeInTheDocument()
        })
    })

    it('does not offer an excluded member', async () => {
        renderSelect({ excludedMembers: [MOCK_SECOND_BASIC_USER.id] })
        await userEvent.click(screen.getByText('Any user'))

        await waitFor(() => expect(screen.getByText(MOCK_DEFAULT_BASIC_USER.first_name)).toBeInTheDocument())
        expect(screen.queryByText(MOCK_SECOND_BASIC_USER.first_name)).not.toBeInTheDocument()
    })

    it('calls onChange with the picked user', async () => {
        renderSelect()
        await userEvent.click(screen.getByText('Any user'))

        await waitFor(() => expect(screen.getByText(MOCK_SECOND_BASIC_USER.first_name)).toBeInTheDocument())
        await userEvent.click(screen.getByText(MOCK_SECOND_BASIC_USER.first_name))

        expect(onChange).toHaveBeenCalledWith(MOCK_SECOND_BASIC_USER)
    })

    it('preserves an open picker search when another picker mounts and clears it after closing', async () => {
        const pickers = (showSecond: boolean): JSX.Element => (
            <Provider>
                <>
                    <MemberSelect value={null} onChange={onChange} />
                    {showSecond ? <MemberSelect value={null} onChange={onChange} /> : null}
                    <button type="button">Outside</button>
                </>
            </Provider>
        )
        const { rerender } = render(pickers(false))

        await userEvent.click(screen.getByText('Any user'))
        const searchInput = await screen.findByPlaceholderText('Search')
        await userEvent.type(searchInput, 'Rose')

        rerender(pickers(true))
        expect(screen.getByPlaceholderText('Search')).toHaveValue('Rose')

        await userEvent.click(screen.getByText('Outside'))
        await waitFor(() => expect(screen.queryByPlaceholderText('Search')).not.toBeInTheDocument())
        await userEvent.click(screen.getAllByText('Any user')[0])

        expect(await screen.findByPlaceholderText('Search')).toHaveValue('')
    })

    it('focuses search and picks a custom option from an external roster', async () => {
        const onSelectOption = jest.fn()
        const onSearch = jest.fn()
        const onForYou = jest.fn()
        renderSelect({
            defaultLabel: 'Entire project',
            extraOptions: [{ label: 'For you', onClick: onForYou }],
            options: [
                { uuid: 'reviewer-1', name: 'Alex', email: '[email protected]' },
                {
                    uuid: MOCK_DEFAULT_BASIC_USER.uuid,
                    name: MOCK_DEFAULT_BASIC_USER.first_name,
                    email: MOCK_DEFAULT_BASIC_USER.email,
                },
            ],
            onSearch,
            onSelectOption,
        })

        await userEvent.click(screen.getByText('Entire project'))
        expect(screen.getByPlaceholderText('Search')).toHaveFocus()
        expect(
            screen.getByText(MOCK_DEFAULT_BASIC_USER.first_name).compareDocumentPosition(screen.getByText('Alex')) &
                Node.DOCUMENT_POSITION_FOLLOWING
        ).toBeTruthy()
        expect(screen.queryByText(MOCK_SECOND_BASIC_USER.first_name)).not.toBeInTheDocument()
        await userEvent.type(screen.getByPlaceholderText('Search'), 'Alex')
        expect(onSearch).toHaveBeenLastCalledWith('Alex')
        await userEvent.click(screen.getByText('Outside'))
        await waitFor(() => expect(screen.queryByPlaceholderText('Search')).not.toBeInTheDocument())
        await userEvent.click(screen.getByText('Entire project'))
        expect(screen.getByPlaceholderText('Search')).toHaveValue('Alex')
        expect(onSearch).toHaveBeenLastCalledWith('Alex')
        await userEvent.click(screen.getByText('Alex'))
        expect(onSelectOption).toHaveBeenCalledWith('reviewer-1', 'Alex')
        expect(onSearch).toHaveBeenLastCalledWith('')

        await userEvent.click(screen.getByText('Entire project'))
        expect(screen.getByPlaceholderText('Search')).toHaveValue('')
        await userEvent.click(screen.getAllByText('Entire project')[1])
        expect(onChange).toHaveBeenCalledWith(null)

        await userEvent.click(screen.getByText('Entire project'))
        await userEvent.click(screen.getByText('For you'))
        expect(onForYou).toHaveBeenCalledTimes(1)
    })
})