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.

1.5 KB
Raw Blame
import { elementToSelector } from 'lib/utils/actions'

import { ElementType } from '~/types'

describe('elementToSelector', () => {
    it('generates a data attr not an #ID', () => {
        const element = {
            attr_id: 'tomato',
        } as ElementType

        const actual = elementToSelector(element, [])
        expect(actual).toEqual('[id="tomato"]')
    })

    it('generates an incorrect class selector', () => {
        const element = {
            attr_class: ['potato', 'soup'],
        } as ElementType

        const actual = elementToSelector(element, [])
        expect(actual).toEqual('.potato.soup')
    })

    const dataAttributeValueCases = [
        {
            name: 'keeps dots unescaped so backend literal matching still works',
            value: 'user.settings.save',
            expected: '[data-attr="user.settings.save"]',
        },
        {
            name: 'escapes quotes so a value cannot break out of the selector',
            value: 'x"],[id="other',
            expected: '[data-attr="x\\"],[id=\\"other"]',
        },
        {
            name: 'escapes backslashes before quotes',
            value: 'a\\"b',
            expected: '[data-attr="a\\\\\\"b"]',
        },
    ]

    it.each(dataAttributeValueCases)('$name', ({ value, expected }) => {
        const element = {
            attributes: { 'attr__data-attr': value },
        } as unknown as ElementType

        const actual = elementToSelector(element, ['data-attr'])
        expect(actual).toEqual(expected)
    })
})