Skip to content
This page is available as Markdown at /editor/guides/testing-behaviors.md. For the full documentation index, see /llms.txt, or the complete corpus at /llms-full.txt.

Testing behaviors

You can test your behaviors against a real editor in a real browser. This guide shows two ways to do it: plain Vitest tests for simple cases, and Gherkin specs run with Racejar, which is how many of the official plugins are tested.

Both approaches use Vitest Browser Mode with Playwright.

Install the testing dependencies:

    Then download the Chromium build that Playwright drives:

    Terminal window
    npx playwright install chromium

    Configure Vitest for Browser Mode in your vitest.config.ts:

    vitest.config.ts
    import {playwright} from '@vitest/browser-playwright'
    import {defineConfig} from 'vitest/config'
    export default defineConfig({
    test: {
    browser: {
    enabled: true,
    provider: playwright(),
    instances: [{browser: 'chromium'}],
    },
    },
    })

    Vitest opens a browser window unless it detects CI. Add headless: true to browser to run without one locally.

    If you use TypeScript, declare .feature file imports:

    global.d.ts
    declare module '*.feature?raw' {
    const content: string
    export default content
    }

    Every test needs an editor on the page and a way to reach the editor instance. Write a small helper for it. It renders EditorProvider and PortableTextEditable with render from vitest-browser-react, and EditorRefPlugin hands you the editor instance through a ref:

    test-editor.tsx
    import {
    EditorProvider,
    PortableTextEditable,
    type Editor,
    type SchemaDefinition,
    } from '@portabletext/editor'
    import {EditorRefPlugin} from '@portabletext/editor/plugins'
    import {createTestKeyGenerator} from '@portabletext/test'
    import {createRef, type ReactNode} from 'react'
    import {expect} from 'vitest'
    import {render} from 'vitest-browser-react'
    export async function createTestEditor(options: {
    schemaDefinition: SchemaDefinition
    children?: ReactNode
    }) {
    const editorRef = createRef<Editor>()
    const screen = await render(
    <EditorProvider
    initialConfig={{
    schemaDefinition: options.schemaDefinition,
    keyGenerator: createTestKeyGenerator(),
    }}
    >
    <EditorRefPlugin ref={editorRef} />
    <PortableTextEditable />
    {options.children}
    </EditorProvider>,
    )
    const locator = screen.getByRole('textbox')
    await expect.element(locator).toBeInTheDocument()
    if (!editorRef.current) {
    throw new Error('The editor did not render')
    }
    return {editor: editorRef.current, locator}
    }

    The helper returns the editor instance and a locator for the editable element. Pass your behaviors or plugins as children. createTestKeyGenerator from @portabletext/test makes the block and span keys predictable (k0, k1, and so on).

    For a simple behavior, render the editor, type into it, and assert on the result:

    uppercase-a.test.tsx
    import {defineSchema} from '@portabletext/editor'
    import {defineBehavior, execute} from '@portabletext/editor/behaviors'
    import {BehaviorPlugin} from '@portabletext/editor/plugins'
    import {getTersePt} from '@portabletext/test'
    import {expect, test, vi} from 'vitest'
    import {userEvent} from 'vitest/browser'
    import {createTestEditor} from './test-editor'
    test('replaces lowercase a with uppercase A', async () => {
    const {editor, locator} = await createTestEditor({
    schemaDefinition: defineSchema({}),
    children: (
    <BehaviorPlugin
    behaviors={[
    defineBehavior({
    on: 'insert.text',
    guard: ({event}) => event.text === 'a',
    actions: [() => [execute({type: 'insert.text', text: 'A'})]],
    }),
    ]}
    />
    ),
    })
    await userEvent.click(locator)
    await userEvent.type(locator, 'a')
    await vi.waitFor(() => {
    expect(getTersePt(editor.getSnapshot().context)).toEqual(['A'])
    })
    })

    Key parts:

    • userEvent from vitest/browser sends real clicks and key presses to the editable element through Playwright.
    • editor.getSnapshot().context holds the current editor state, including value (the Portable Text array), selection, and schema.
    • getTersePt from @portabletext/test turns the value into a compact array of strings, one per block. Commas separate spans, so ['foo,bar'] is one block with two spans.
    • vi.waitFor retries the assertion, because the editor applies typed text asynchronously.

    To spec a behavior end to end, write Gherkin feature files and run them with Racejar. Racejar compiles each scenario into a Vitest test and runs your step definitions for its steps. You write the step definitions yourself, so they can use the same editor API as the quick start.

    The example below tests the em dash rule from @portabletext/plugin-typography, which turns -- into —. To follow along, install it:

    Terminal window
    npm i @portabletext/plugin-typography

    Describe the behavior in plain English:

    em-dash.feature
    Feature: Em dash
    Scenario: Typing a second hyphen inserts an em dash
    Given the editor state is "B: foo-"
    When "-" is typed
    Then the editor state is "B: foo—"
    When undo is performed
    Then the editor state is "B: foo--"
    Scenario: The em dash keeps the decorator of the text it replaces
    Given the editor state is "B: [strong:foo-]"
    When "-" is typed
    Then the editor state is "B: [strong:foo—]"

    Gherkin scenarios follow the Given/When/Then pattern:

    • Given sets up the editor state.
    • When performs actions, like typing or undo.
    • Then asserts the result.

    The quoted editor states use textspec notation, which @portabletext/test reads and writes. B: foo- is one text block with the text foo-, and [strong:foo-] is text with the strong decorator.

    Each step in the feature file needs a step definition. Define them with Given, When, and Then from racejar. The context object is shared by the steps of one scenario:

    steps.ts
    import type {Editor} from '@portabletext/editor'
    import {fromTextspec, toTextspec} from '@portabletext/test'
    import {Given, Then, When} from 'racejar'
    import {expect, vi} from 'vitest'
    import {userEvent} from 'vitest/browser'
    export type Context = {
    editor: Editor
    }
    export const stepDefinitions = [
    Given('the editor state is {string}', (context: Context, state: string) => {
    const {schema, keyGenerator} = context.editor.getSnapshot().context
    const {blocks} = fromTextspec({schema, keyGenerator}, state)
    context.editor.send({type: 'focus'})
    context.editor.send({
    type: 'insert.blocks',
    blocks,
    placement: 'auto',
    select: 'end',
    })
    }),
    When('{string} is typed', async (_context: Context, text: string) => {
    await userEvent.keyboard(text)
    }),
    When('undo is performed', (context: Context) => {
    context.editor.send({type: 'history.undo'})
    }),
    Then(
    'the editor state is {string}',
    async (context: Context, state: string) => {
    await vi.waitFor(() => {
    const {schema, value} = context.editor.getSnapshot().context
    expect(
    toTextspec({schema, value, selection: null}, {singleLine: true}),
    ).toEqual(state)
    })
    },
    ),
    ]

    The Given step focuses the editor, then inserts the blocks and puts the caret at the end of them. The When step types at the caret with userEvent.keyboard. Clicking the editable instead would move the caret to where the click lands.

    Connect the feature file, the step definitions, and the editor in a test file. A Before hook renders a fresh editor for each scenario:

    em-dash.test.tsx
    import {defineSchema} from '@portabletext/editor'
    import {TypographyPlugin} from '@portabletext/plugin-typography'
    import {Before} from 'racejar'
    import {Feature} from 'racejar/vitest'
    import emDashFeature from './em-dash.feature?raw'
    import {stepDefinitions, type Context} from './steps'
    import {createTestEditor} from './test-editor'
    Feature({
    featureText: emDashFeature,
    hooks: [
    Before(async (context: Context) => {
    const {editor} = await createTestEditor({
    schemaDefinition: defineSchema({decorators: [{name: 'strong'}]}),
    children: <TypographyPlugin />,
    })
    context.editor = editor
    }),
    ],
    stepDefinitions,
    })
    Terminal window
    npx vitest run

    Each scenario becomes a separate test case. When a step fails, the error points to the assertion inside that step’s definition.

    As your features grow, add steps where you need them. A step can live next to the test that uses it and be passed alongside your shared steps. This one inserts several characters in a single event, the way Android keyboards often do:

    em-dash-insert.test.tsx
    import {defineSchema} from '@portabletext/editor'
    import {TypographyPlugin} from '@portabletext/plugin-typography'
    import {Before, When} from 'racejar'
    import {Feature} from 'racejar/vitest'
    import emDashInsertFeature from './em-dash-insert.feature?raw'
    import {stepDefinitions, type Context} from './steps'
    import {createTestEditor} from './test-editor'
    const insertStep = When(
    '{string} is inserted',
    (context: Context, text: string) => {
    context.editor.send({type: 'insert.text', text})
    },
    )
    Feature({
    featureText: emDashInsertFeature,
    hooks: [
    Before(async (context: Context) => {
    const {editor} = await createTestEditor({
    schemaDefinition: defineSchema({decorators: [{name: 'strong'}]}),
    children: <TypographyPlugin />,
    })
    context.editor = editor
    }),
    ],
    stepDefinitions: [...stepDefinitions, insertStep],
    })
    em-dash-insert.feature
    Feature: Em dash on Android
    Scenario: Inserting two hyphens at once inserts an em dash
    Given the editor state is "B: foo"
    When "--" is inserted
    Then the editor state is "B: foo—"

    Racejar throws an error if a step in the feature file has no matching definition, or if more than one definition matches it.