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.

test(workflows): RTL + Playwright coverage for HogFlowTaxonomicFilters and category dropdown fix (#57470)

posthog[bot]dce4c7a414cd
diff --git a/frontend/src/lib/components/TaxonomicFilter/CategoryDropdown.tsx b/frontend/src/lib/components/TaxonomicFilter/CategoryDropdown.tsx
index 4d21c4ffe85e..b6c5bc939c95 100644
--- a/frontend/src/lib/components/TaxonomicFilter/CategoryDropdown.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/CategoryDropdown.tsx
@@ -5,6 +5,7 @@ import { useCallback } from 'react'
import { IconChevronDown } from '@posthog/icons'
import { FEATURE_FLAGS } from 'lib/constants'
+import { CLICK_OUTSIDE_BLOCK_CLASS } from 'lib/hooks/useOutsideClickHandler'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonMenu, LemonMenuItem } from 'lib/lemon-ui/LemonMenu'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
@@ -68,7 +69,7 @@ export function CategoryDropdown({
onVisibilityChange={onVisibilityChange}
activeItemIndex={activeItemIndex >= 0 ? activeItemIndex : undefined}
placement="bottom-start"
- className="click-outside-block"
+ className={CLICK_OUTSIDE_BLOCK_CLASS}
>
{renderTrigger(variant, activeLabel)}
</LemonMenu>
@@ -83,6 +84,7 @@ function renderTrigger(variant: Exclude<CategoryDropdownVariant, 'control'>, act
sideIcon={<IconChevronDown />}
data-attr={`taxonomic-category-dropdown-trigger-${variant}`}
aria-label={`Current category: ${activeLabel}. Click to change.`}
+ className={CLICK_OUTSIDE_BLOCK_CLASS}
>
{activeLabel}
</LemonButton>
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts
index d0b3f0954f1a..7caa08a23753 100644
--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts
@@ -456,6 +456,90 @@ describe('taxonomicFilterLogic', () => {
})
})
+ describe('WorkflowVariables in SuggestedFilters', () => {
+ // The All/Suggestions tab is always prepended to the workflow scene's filter via
+ // `TaxonomicPropertyFilter`, and is the default landing tab. Surfacing workflow variables
+ // there (and ordering them first) avoids users landing on an empty-feeling tab when their
+ // query matches a defined variable.
+ it('surfaces workflow variables via optionsFromProp and orders them first in redistributed top matches', async () => {
+ const logicProps: TaxonomicFilterLogicProps = {
+ taxonomicFilterLogicKey: 'testWorkflowVariablesSuggested',
+ taxonomicGroupTypes: [
+ TaxonomicFilterGroupType.SuggestedFilters,
+ TaxonomicFilterGroupType.WorkflowVariables,
+ TaxonomicFilterGroupType.Events,
+ ],
+ optionsFromProp: {
+ [TaxonomicFilterGroupType.WorkflowVariables]: [{ name: 'event_name' }, { name: 'unrelated_var' }],
+ },
+ }
+ const workflowLogicTest = taxonomicFilterLogic(logicProps)
+ workflowLogicTest.mount()
+ for (const listGroupType of logicProps.taxonomicGroupTypes) {
+ infiniteListLogic({ ...logicProps, listGroupType }).mount()
+ }
+
+ expect(workflowLogicTest.values.activeTab).toBe(TaxonomicFilterGroupType.SuggestedFilters)
+
+ // The query "event" matches both the WorkflowVariables option `event_name` and any
+ // events in the mocked event_definitions endpoint. WorkflowVariables must come first.
+ await expectLogic(workflowLogicTest, () => {
+ workflowLogicTest.actions.setSearchQuery('event')
+ })
+ .toDispatchActions(['setSearchQuery', 'appendTopMatches'])
+ .delay(1)
+
+ const redistributed = workflowLogicTest.values.redistributedTopMatchItems
+ const groupOrder = redistributed.map((item) => item.group)
+ const firstWorkflowIndex = groupOrder.indexOf(TaxonomicFilterGroupType.WorkflowVariables)
+ const firstEventsIndex = groupOrder.indexOf(TaxonomicFilterGroupType.Events)
+
+ expect(firstWorkflowIndex).toBeGreaterThanOrEqual(0)
+ expect(redistributed[firstWorkflowIndex]).toEqual(
+ expect.objectContaining({
+ name: 'event_name',
+ group: TaxonomicFilterGroupType.WorkflowVariables,
+ })
+ )
+ // Workflow variables come before events in the redistributed order.
+ if (firstEventsIndex !== -1) {
+ expect(firstWorkflowIndex).toBeLessThan(firstEventsIndex)
+ }
+
+ workflowLogicTest.unmount()
+ })
+
+ it('does not surface workflow variables in SuggestedFilters when no variables are defined', async () => {
+ const logicProps: TaxonomicFilterLogicProps = {
+ taxonomicFilterLogicKey: 'testWorkflowVariablesEmpty',
+ taxonomicGroupTypes: [
+ TaxonomicFilterGroupType.SuggestedFilters,
+ TaxonomicFilterGroupType.WorkflowVariables,
+ TaxonomicFilterGroupType.Events,
+ ],
+ optionsFromProp: {
+ [TaxonomicFilterGroupType.WorkflowVariables]: [],
+ },
+ }
+ const workflowLogicTest = taxonomicFilterLogic(logicProps)
+ workflowLogicTest.mount()
+ for (const listGroupType of logicProps.taxonomicGroupTypes) {
+ infiniteListLogic({ ...logicProps, listGroupType }).mount()
+ }
+
+ await expectLogic(workflowLogicTest, () => {
+ workflowLogicTest.actions.setSearchQuery('event')
+ })
+ .toDispatchActions(['setSearchQuery'])
+ .delay(1)
+
+ const groups = workflowLogicTest.values.redistributedTopMatchItems.map((item) => item.group)
+ expect(groups).not.toContain(TaxonomicFilterGroupType.WorkflowVariables)
+
+ workflowLogicTest.unmount()
+ })
+ })
+
describe('SuggestedFilters presence', () => {
it.each([
{
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
index 792bb2cd9fb6..52b76898d851 100644
--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
@@ -643,6 +643,11 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([
type: TaxonomicFilterGroupType.WorkflowVariables,
categoryLabel: () => 'Workflow variables',
render: HogFlowTaxonomicFilters,
+ // Populated via optionsFromProp from the workflow scene so the All/Suggestions
+ // tab can aggregate workflow variables alongside other groups. The render
+ // override above still drives the dedicated tab UI.
+ getName: (option: SimpleOption) => option.name,
+ getValue: (option: SimpleOption) => option.name,
getPopoverHeader: () => 'Workflow variables',
},
{
diff --git a/playwright/e2e/workflows-property-filter-category-dropdown.spec.ts b/playwright/e2e/workflows-property-filter-category-dropdown.spec.ts
new file mode 100644
index 000000000000..61c73613ce2e
--- /dev/null
+++ b/playwright/e2e/workflows-property-filter-category-dropdown.spec.ts
@@ -0,0 +1,149 @@
+import { expect } from '@playwright/test'
+
+import { mockFeatureFlags } from '../utils/mockApi'
+import { test } from '../utils/playwright-test-base'
+
+const TRIGGER_NODE_ID = 'trigger_node'
+const EXIT_NODE_ID = 'exit_node'
+const CONDITIONAL_BRANCH_ID = 'conditional_branch_node'
+
+function buildConditionalBranchWorkflow(): Record<string, any> {
+ return {
+ name: `Property filter category dropdown bug ${Date.now()}`,
+ actions: [
+ {
+ id: TRIGGER_NODE_ID,
+ type: 'trigger',
+ name: 'Trigger',
+ description: 'Triggered by an event',
+ created_at: 0,
+ updated_at: 0,
+ config: {
+ type: 'event',
+ filters: { events: [{ id: '$pageview', type: 'events' }] },
+ },
+ },
+ {
+ id: CONDITIONAL_BRANCH_ID,
+ type: 'conditional_branch',
+ name: 'Conditional branch',
+ description: 'Branch on event property',
+ created_at: 0,
+ updated_at: 0,
+ config: {
+ conditions: [
+ {
+ filters: {
+ properties: [
+ {
+ key: '$browser',
+ type: 'event',
+ value: 'Chrome',
+ operator: 'exact',
+ },
+ ],
+ },
+ },
+ ],
+ },
+ },
+ {
+ id: EXIT_NODE_ID,
+ type: 'exit',
+ name: 'Exit',
+ description: 'Default exit',
+ created_at: 0,
+ updated_at: 0,
+ config: { reason: 'Default exit' },
+ },
+ ],
+ edges: [
+ { from: TRIGGER_NODE_ID, to: CONDITIONAL_BRANCH_ID, type: 'continue' },
+ { from: CONDITIONAL_BRANCH_ID, to: EXIT_NODE_ID, type: 'branch', index: 0 },
+ { from: CONDITIONAL_BRANCH_ID, to: EXIT_NODE_ID, type: 'continue' },
+ ],
+ conversion: { window_minutes: null, filters: [] },
+ exit_condition: 'exit_only_at_end',
+ version: 1,
+ status: 'draft',
+ }
+}
+
+test.describe('Workflows conditional branch property filter category dropdown', () => {
+ test.beforeEach(async ({ page }) => {
+ await mockFeatureFlags(page, {
+ 'taxonomic-filter-category-dropdown': 'pill',
+ })
+ })
+
+ test('reopening a saved filter and clicking the category dropdown trigger pill keeps the filter popover open', async ({
+ page,
+ }) => {
+ test.setTimeout(90 * 1000)
+ const me = await page.request.get('/api/users/@me/')
+ expect(me.ok()).toBe(true)
+ const meData = await me.json()
+ const teamId: number = meData.team.id
+
+ const workflowPayload = buildConditionalBranchWorkflow()
+ const workflowId = await page.evaluate(
+ async ({ teamId, payload }) => {
+ const csrfToken =
+ document.cookie
+ .split(';')
+ .map((c) => c.trim())
+ .find((c) => c.startsWith('posthog_csrftoken='))
+ ?.split('=')
+ .slice(1)
+ .join('=') || ''
+ if (!csrfToken) {
+ throw new Error('CSRF cookie missing')
+ }
+ const response = await fetch(`/api/environments/${teamId}/hog_flows/`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': decodeURIComponent(csrfToken),
+ },
+ body: JSON.stringify(payload),
+ })
+ if (!response.ok) {
+ throw new Error(`hog_flows POST failed: ${response.status} ${await response.text()}`)
+ }
+ const data = await response.json()
+ return data.id as string
+ },
+ { teamId, payload: workflowPayload }
+ )
+
+ await test.step('open the workflow editor and select the conditional branch', async () => {
+ await page.goto(`/workflows/${workflowId}/workflow`)
+ await page.waitForSelector('[data-attr="workflow-editor"]', { timeout: 30000 })
+ await page.locator(`[data-testid="rf__node-${CONDITIONAL_BRANCH_ID}"]`).click()
+ await expect(page.getByTestId('property-filter-0')).toBeVisible()
+ })
+
+ await test.step('reopen the saved filter popover', async () => {
+ await page.getByTestId('property-filter-0').locator('.PropertyFilterButton').click()
+ await expect(page.getByTestId('property-select-toggle-0')).toBeVisible()
+ })
+
+ await test.step('open the inner taxonomic filter dropdown', async () => {
+ await page.getByTestId('property-select-toggle-0').click()
+ await expect(page.getByTestId('taxonomic-filter-searchfield')).toBeVisible()
+ await expect(page.getByTestId('taxonomic-category-dropdown-trigger-pill')).toBeVisible()
+ })
+
+ await test.step('clicking the category dropdown trigger pill opens the menu and keeps the popover open', async () => {
+ await page.getByTestId('taxonomic-category-dropdown-trigger-pill').click()
+ // Give the popover transitions time to settle so the assertions reflect the steady state
+ // after the click rather than the brief moment between mouseup and click-outside.
+ await page.waitForTimeout(250)
+ await expect(page.getByTestId('property-filter-0')).toBeVisible()
+ await expect(page.getByTestId('property-select-toggle-0')).toBeVisible()
+ await expect(page.getByTestId('taxonomic-filter-searchfield')).toBeVisible()
+ await expect(page.getByTestId('taxonomic-category-dropdown-item-event_properties')).toBeVisible()
+ })
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx b/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx
index 12ee729180b4..b5b5638466b3 100644
--- a/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx
@@ -59,14 +59,18 @@ export function HogFlowEventFilters({ filters, setFilters, typeKey, buttonCopy }
actionsTaxonomicGroupTypes.push(TaxonomicFilterGroupType.InternalEvents)
}
+ // WorkflowVariables comes first so its dedicated tab renders first in the category list.
+ // ActionFilter does not pipe `taxonomicFilterOptionsFromProp`, so the All/Suggestions tab
+ // does not aggregate variables here — variable surfacing in All/Suggestions only kicks in
+ // for the property-level filter (HogFlowPropertyFilters below).
const propertyTaxonomicGroupTypes = [
+ TaxonomicFilterGroupType.WorkflowVariables,
TaxonomicFilterGroupType.EventProperties,
TaxonomicFilterGroupType.EventFeatureFlags,
TaxonomicFilterGroupType.Elements,
TaxonomicFilterGroupType.PersonProperties,
...groupsTaxonomicTypes,
TaxonomicFilterGroupType.HogQLExpression,
- TaxonomicFilterGroupType.WorkflowVariables,
]
if (shouldShowInternalEvents) {
propertyTaxonomicGroupTypes.push(TaxonomicFilterGroupType.InternalEventProperties)
@@ -101,6 +105,14 @@ export function HogFlowEventFilters({ filters, setFilters, typeKey, buttonCopy }
export function HogFlowPropertyFilters({ filtersKey, filters, setFilters }: HogFlowFiltersProps): JSX.Element {
const sampleGlobals = useSampleGlobals()
const { groupsTaxonomicTypes } = useValues(groupsModel)
+ const { workflow } = useValues(workflowLogic)
+ // Surface workflow variables in the All/Suggestions tab so a user searching by variable key
+ // sees a match alongside event/person properties. The dedicated tab still works without this.
+ const taxonomicFilterOptionsFromProp = {
+ [TaxonomicFilterGroupType.WorkflowVariables]: (workflow?.variables ?? []).map((variable) => ({
+ name: variable.key,
+ })),
+ }
return (
<PropertyFilters
propertyFilters={filters?.properties}
@@ -117,6 +129,7 @@ export function HogFlowPropertyFilters({ filtersKey, filters, setFilters }: HogF
TaxonomicFilterGroupType.HogQLExpression,
TaxonomicFilterGroupType.EventMetadata,
]}
+ taxonomicFilterOptionsFromProp={taxonomicFilterOptionsFromProp}
metadataSource={{
kind: NodeKind.EventsQuery,
select: defaultDataTableColumns(NodeKind.EventsQuery),
diff --git a/products/workflows/frontend/Workflows/hogflows/filters/HogFlowPropertyFiltersSearch.test.tsx b/products/workflows/frontend/Workflows/hogflows/filters/HogFlowPropertyFiltersSearch.test.tsx
new file mode 100644
index 000000000000..ed3c1ace47aa
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/filters/HogFlowPropertyFiltersSearch.test.tsx
@@ -0,0 +1,146 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { Provider } from 'kea'
+
+import { recentTaxonomicFiltersLogic } from 'lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { actionsModel } from '~/models/actionsModel'
+import { groupsModel } from '~/models/groupsModel'
+import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
+import { initKeaTests } from '~/test/init'
+import { mockActionDefinition, mockGetEventDefinitions, mockGetPropertyDefinitions } from '~/test/mocks'
+
+import { workflowLogic } from '../../workflowLogic'
+import { HogFlowAction } from '../types'
+import { HogFlowPropertyFilters } from './HogFlowFilters'
+
+jest.mock('lib/components/AutoSizer', () => ({
+ AutoSizer: ({ renderProp }: { renderProp: (size: { height: number; width: number }) => React.ReactNode }) =>
+ renderProp({ height: 400, width: 400 }),
+}))
+
+const ORDER_ID_VARIABLE = { type: 'string' as const, key: 'order_id', label: 'Order ID', default_value: '' }
+const CART_TOTAL_VARIABLE = { type: 'number' as const, key: 'cart_total', label: 'Cart total', default_value: 0 }
+const SHIPPING_COUNTRY_VARIABLE = {
+ type: 'string' as const,
+ key: 'shipping_country',
+ label: 'Shipping country',
+ default_value: '',
+}
+
+describe('HogFlowPropertyFilters search', () => {
+ let unmountWorkflowLogic: (() => void) | null = null
+ let mountedWorkflowLogic: ReturnType<typeof workflowLogic.build> | null = null
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team/event_definitions': mockGetEventDefinitions,
+ '/api/projects/:team/property_definitions': mockGetPropertyDefinitions,
+ '/api/projects/:team/actions': { results: [mockActionDefinition] },
+ '/api/environments/:team/persons/properties': [],
+ '/api/environments/:team/events/values': { results: [], refreshing: false },
+ '/api/environments/:team_id/quick_filters/': { results: [] },
+ },
+ post: {
+ '/api/environments/:team/query': { results: [] },
+ },
+ })
+ initKeaTests()
+ actionsModel.mount()
+ groupsModel.mount()
+ propertyDefinitionsModel.mount()
+ recentTaxonomicFiltersLogic.mount()
+ mountedWorkflowLogic = workflowLogic({ id: 'new', tabId: 'default' })
+ unmountWorkflowLogic = mountedWorkflowLogic.mount()
+ })
+
+ afterEach(() => {
+ unmountWorkflowLogic?.()
+ unmountWorkflowLogic = null
+ mountedWorkflowLogic = null
+ cleanup()
+ })
+
+ function setWorkflowVariables(variables: Array<Record<string, unknown>>): void {
+ mountedWorkflowLogic!.actions.setWorkflowInfo({ variables: variables as any })
+ }
+
+ function renderFilters(): { setFilters: jest.Mock } {
+ const setFilters = jest.fn()
+ const filters = { properties: [] } as HogFlowAction['filters']
+ render(
+ <Provider>
+ <HogFlowPropertyFilters filtersKey="search-test" filters={filters} setFilters={setFilters} />
+ </Provider>
+ )
+ return { setFilters }
+ }
+
+ async function openTaxonomicFilter(): Promise<void> {
+ fireEvent.click(screen.getByTestId('new-prop-filter-HogFlowPropertyFilters.search-test'))
+ await waitFor(() => {
+ expect(screen.getByTestId('taxonomic-filter-searchfield')).toBeInTheDocument()
+ })
+ }
+
+ function search(query: string): void {
+ fireEvent.change(screen.getByTestId('taxonomic-filter-searchfield'), { target: { value: query } })
+ }
+
+ it('shows workflow variables in the dedicated tab', async () => {
+ setWorkflowVariables([ORDER_ID_VARIABLE, CART_TOTAL_VARIABLE])
+ renderFilters()
+
+ await openTaxonomicFilter()
+ fireEvent.click(screen.getByTestId('taxonomic-tab-workflow_variables'))
+
+ await waitFor(() => {
+ expect(screen.getAllByRole('button', { name: 'order_id' }).length).toBeGreaterThan(0)
+ })
+ expect(screen.getAllByRole('button', { name: 'cart_total' }).length).toBeGreaterThan(0)
+ })
+
+ it('filters workflow variables by search query in the dedicated tab', async () => {
+ setWorkflowVariables([ORDER_ID_VARIABLE, CART_TOTAL_VARIABLE, SHIPPING_COUNTRY_VARIABLE])
+ renderFilters()
+
+ await openTaxonomicFilter()
+ fireEvent.click(screen.getByTestId('taxonomic-tab-workflow_variables'))
+ search('cart')
+
+ await waitFor(() => {
+ expect(screen.getAllByRole('button', { name: 'cart_total' }).length).toBeGreaterThan(0)
+ })
+ expect(screen.queryByRole('button', { name: 'order_id' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'shipping_country' })).not.toBeInTheDocument()
+ })
+
+ it('surfaces workflow variables in the All/Suggestions tab when searching', async () => {
+ setWorkflowVariables([ORDER_ID_VARIABLE, CART_TOTAL_VARIABLE])
+ renderFilters()
+
+ await openTaxonomicFilter()
+ search('order')
+
+ await waitFor(() => {
+ expect(screen.getByTestId('prop-filter-workflow_variables-0')).toBeInTheDocument()
+ })
+ expect(screen.getByTestId('prop-filter-workflow_variables-0')).toHaveTextContent('order_id')
+ })
+
+ it('shows an empty state in the workflow variables tab when no variables match the search', async () => {
+ setWorkflowVariables([ORDER_ID_VARIABLE])
+ renderFilters()
+
+ await openTaxonomicFilter()
+ fireEvent.click(screen.getByTestId('taxonomic-tab-workflow_variables'))
+ search('zzznonexistent')
+
+ await waitFor(() => {
+ expect(screen.getAllByText('No workflow variables match your search.').length).toBeGreaterThan(0)
+ })
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/filters/HogFlowTaxonomicFilters.test.tsx b/products/workflows/frontend/Workflows/hogflows/filters/HogFlowTaxonomicFilters.test.tsx
new file mode 100644
index 000000000000..615f9a50f36b
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/filters/HogFlowTaxonomicFilters.test.tsx
@@ -0,0 +1,147 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { useValues } from 'kea'
+
+import { infiniteListLogic } from 'lib/components/TaxonomicFilter/infiniteListLogic'
+import { InfiniteListLogicProps, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+
+import { PropertyFilterType } from '~/types'
+
+import { workflowLogic } from '../../workflowLogic'
+import { HogFlowTaxonomicFilters } from './HogFlowTaxonomicFilters'
+
+jest.mock('kea', () => ({
+ ...jest.requireActual('kea'),
+ useValues: jest.fn(),
+}))
+
+jest.mock('lib/components/TaxonomicFilter/infiniteListLogic', () => ({
+ infiniteListLogic: jest.fn(),
+}))
+
+jest.mock('../../workflowLogic', () => ({
+ workflowLogic: { __mock: 'workflowLogic' },
+}))
+
+const mockedUseValues = useValues as jest.Mock
+const mockedInfiniteListLogic = infiniteListLogic as unknown as jest.Mock
+
+const INFINITE_LIST_LOGIC_PROPS: InfiniteListLogicProps = {
+ taxonomicFilterLogicKey: 'test-key',
+ listGroupType: TaxonomicFilterGroupType.WorkflowVariables,
+ taxonomicGroupTypes: [TaxonomicFilterGroupType.WorkflowVariables],
+}
+
+const VARIABLE_FOO = {
+ type: 'string' as const,
+ key: 'foo_var',
+ label: 'Foo variable',
+}
+const VARIABLE_BAR = {
+ type: 'number' as const,
+ key: 'bar_var',
+ label: 'Bar variable',
+}
+const VARIABLE_BAZ = {
+ type: 'string' as const,
+ key: 'baz_var',
+ label: 'Hello world',
+}
+
+function setupMocks({
+ variables,
+ trimmedSearchQuery = '',
+}: {
+ variables: Array<Record<string, unknown>> | undefined
+ trimmedSearchQuery?: string
+}): void {
+ const infiniteListLogicRef = { __mock: 'infiniteListLogicInstance' }
+ mockedInfiniteListLogic.mockReturnValue(infiniteListLogicRef)
+
+ mockedUseValues.mockImplementation((logic: unknown) => {
+ if (logic === workflowLogic) {
+ return { workflow: variables === undefined ? null : { variables } }
+ }
+ if (logic === infiniteListLogicRef) {
+ return { trimmedSearchQuery }
+ }
+ return {}
+ })
+}
+
+function renderComponent(): { onChange: jest.Mock } {
+ const onChange = jest.fn()
+ render(<HogFlowTaxonomicFilters onChange={onChange} infiniteListLogicProps={INFINITE_LIST_LOGIC_PROPS} />)
+ return { onChange }
+}
+
+describe('HogFlowTaxonomicFilters', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it.each([
+ { description: 'workflow has no variables', variables: [] as Array<Record<string, unknown>> },
+ { description: 'workflow is null', variables: undefined },
+ ])('renders the no-variables empty state when $description', ({ variables }) => {
+ setupMocks({ variables })
+ renderComponent()
+ expect(screen.getByText('No workflow variables defined.')).toBeInTheDocument()
+ })
+
+ it.each([
+ {
+ description: 'renders all variables when the search query is empty',
+ variables: [VARIABLE_FOO, VARIABLE_BAR, VARIABLE_BAZ],
+ trimmedSearchQuery: '',
+ visible: ['foo_var', 'bar_var', 'baz_var'],
+ hidden: ['No workflow variables match your search.'],
+ },
+ {
+ description: 'filters by key (case-insensitive)',
+ variables: [VARIABLE_FOO, VARIABLE_BAR],
+ trimmedSearchQuery: 'FOO',
+ visible: ['foo_var'],
+ hidden: ['bar_var'],
+ },
+ {
+ description: 'filters by label',
+ variables: [VARIABLE_FOO, VARIABLE_BAR, VARIABLE_BAZ],
+ trimmedSearchQuery: 'hello',
+ visible: ['baz_var'],
+ hidden: ['foo_var', 'bar_var'],
+ },
+ {
+ description: 'renders a friendly empty state when no variables match the search',
+ variables: [VARIABLE_FOO, VARIABLE_BAR],
+ trimmedSearchQuery: 'nope',
+ visible: ['No workflow variables match your search.'],
+ hidden: ['foo_var'],
+ },
+ ])('$description', ({ variables, trimmedSearchQuery, visible, hidden }) => {
+ setupMocks({ variables, trimmedSearchQuery })
+ renderComponent()
+ visible.forEach((text) => expect(screen.getByText(text)).toBeInTheDocument())
+ hidden.forEach((text) => expect(screen.queryByText(text)).not.toBeInTheDocument())
+ })
+
+ it('calls onChange with the workflow variable filter group when a variable is clicked', () => {
+ setupMocks({ variables: [VARIABLE_FOO] })
+ const { onChange } = renderComponent()
+
+ fireEvent.click(screen.getByText('foo_var'))
+
+ expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange).toHaveBeenCalledWith('foo_var', {
+ key: 'foo_var',
+ name: 'foo_var',
+ propertyFilterType: PropertyFilterType.WorkflowVariable,
+ taxonomicFilterGroup: TaxonomicFilterGroupType.WorkflowVariables,
+ })
+ })
+})