All files / core/blong-browser/src/components/TestRun TestRunPage.tsx

85.29% Statements 58/68
74% Branches 37/50
86.66% Functions 13/15
88.13% Lines 52/59

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249                                                                                                                  7x 24x                         13x 5x   13x 13x 13x 13x 13x 13x   13x   5x               13x           13x   5x 5x 5x 3x         13x 4x 4x 4x 4x 4x 4x 4x     13x 4x 4x       4x 4x 4x 4x     4x 2x 2x         2x                   2x 2x 1x     1x             3x 3x 3x 4x 7x 7x   4x   1x 1x       13x                                         4x                                                                                                              
/**
 * TestRunPage — the picker around the console.
 *
 * The host supplies a catalog and a loader; the page never lets the user name an arbitrary method,
 * so only a scenario the host listed can be run. The loader is the host's registry lookup; it is
 * called with a catalog method, never with a free-form string.
 */
import type {IMeta, StepArray} from '@feasibleone/blong-chain/browser.ts';
import {useEffect, useMemo, useRef, useState} from 'react';
import {Dropdown} from '../../primereact/index.js';
import type {ITestRunEvent, ITestRunModel, ITestSourceLinkConfig} from '../../types/testRun.js';
import {Button} from '../Button/Button.js';
import {Text} from '../Text/Text.js';
import {BrowserTestRunSource, pendingBrowserRun} from './browserTestRunSource.js';
import {PollingTestRunSource, type ITestRunServerTransport} from './pollingTestRunSource.js';
import {TestRun} from './TestRun.js';
import './TestRunPage.css';
 
export interface ITestRunCatalogEntry {
    /** Wire name of the test group, e.g. `test.session.flow`. */
    method: string;
    /** Display name shown in the picker. */
    name: string;
    /** Where the steps run; browser by default. */
    host?: 'browser' | 'server';
    /** Groups the scenario covers, when the host knows them. */
    groups?: string[];
    description?: string;
}
 
export interface ITestRunPageProps {
    /** The scenarios the page may run. Nothing outside this list is ever loaded. */
    catalog: ITestRunCatalogEntry[];
    /** Resolve a browser catalog method to its step array (the host's registry lookup). */
    load?(method: string): StepArray | Promise<StepArray>;
    /** The transport for server-hosted entries; required when the catalog names one. */
    transport?: ITestRunServerTransport;
    /** Forwarded to the run; usually the logged-in user's meta. */
    $meta?: IMeta;
    /** Base and scheme for source links in the console. */
    sourceLink?: ITestSourceLinkConfig;
    title?: string;
    defaultDetailsOpen?: boolean;
    /** Write the final model and event stream into hidden nodes for a Playwright capture. */
    capture?: boolean;
    className?: string;
}
 
/** JSON for a capture, falling back to a marker rather than throwing on a circular result. */
function captureJson(value: unknown): string {
    try {
        return JSON.stringify(value);
    } catch {
        return JSON.stringify({truncated: true});
    }
}
 
const entryKey = (entry: ITestRunCatalogEntry): string =>
    `${entry.host ?? 'browser'}:${entry.method}`;
 
export function TestRunPage({
    catalog,
    load,
    transport,
    $meta,
    sourceLink,
    title = 'Test run',
    defaultDetailsOpen,
    capture = false,
    className,
}: ITestRunPageProps) {
    const [method, setMethod] = useState<string | undefined>(() =>
        catalog[0] ? entryKey(catalog[0]) : undefined,
    );
    const [run, setRun] = useState<ITestRunModel | undefined>();
    const [busy, setBusy] = useState(false);
    const [error, setError] = useState<string | undefined>();
    const sourceRef = useRef<BrowserTestRunSource | PollingTestRunSource | undefined>(undefined);
    const unsubscribeRef = useRef<(() => void) | undefined>(undefined);
    const eventsRef = useRef<ITestRunEvent[]>([]);
 
    const options = useMemo(
        () =>
            catalog.map(entry => ({
                label: entry.name,
                value: entryKey(entry),
            })),
        [catalog],
    );
 
    const selectedMethod =
        method && catalog.some(entry => entryKey(entry) === method)
            ? method
            : catalog[0]
              ? entryKey(catalog[0])
              : undefined;
 
    useEffect(
        () => () => {
            unsubscribeRef.current?.();
            const source = sourceRef.current;
            if (source instanceof PollingTestRunSource) void source.cancel();
            else void source?.stop();
        },
        [],
    );
 
    const stop = (): void => {
        unsubscribeRef.current?.();
        unsubscribeRef.current = undefined;
        const source = sourceRef.current;
        Iif (source instanceof PollingTestRunSource) void source.cancel();
        else void source?.stop();
        sourceRef.current = undefined;
        setBusy(false);
    };
 
    const start = async (): Promise<void> => {
        const entry = catalog.find(item => entryKey(item) === selectedMethod);
        Iif (!entry) {
            setError('Select a scenario from the catalog');
            return;
        }
        stop();
        setError(undefined);
        setBusy(true);
        try {
            let source: BrowserTestRunSource | PollingTestRunSource;
            let initialRun: ITestRunModel | undefined;
            if (entry.host === 'server') {
                Iif (!transport) throw new Error('No server transport is configured');
                source = new PollingTestRunSource({
                    transport,
                    method: entry.method,
                    $meta,
                });
                initialRun = {
                    ...pendingBrowserRun({
                        name: entry.name,
                        method: entry.method,
                        steps: [],
                        $meta,
                    }),
                    host: 'server',
                };
            } else {
                Iif (!load) throw new Error('No browser loader is configured');
                const steps = await load(entry.method);
                Iif (!Array.isArray(steps)) {
                    throw new Error(`"${entry.method}" did not return a step array`);
                }
                source = new BrowserTestRunSource({
                    name: entry.name,
                    method: entry.method,
                    steps,
                    $meta,
                });
            }
            sourceRef.current = source;
            eventsRef.current = [];
            setRun(initialRun ?? source.snapshot());
            unsubscribeRef.current = source.subscribe(event => {
                eventsRef.current.push(event);
                setRun(source.snapshot());
            });
            void source.start().finally(() => setBusy(false));
        } catch (reason) {
            setError((reason as Error)?.message ?? String(reason));
            setBusy(false);
        }
    };
 
    return (
        <div className={['blong-test-run-page', className ?? ''].filter(Boolean).join(' ')}>
            <header className="blong-test-run-page__bar">
                <span className="blong-test-run-page__title">
                    <Text>{title}</Text>
                </span>
                <Dropdown
                    value={selectedMethod}
                    options={options}
                    onChange={event => setMethod((event.value as string | null) ?? undefined)}
                    placeholder="Select a scenario"
                    aria-label="Scenario"
                    className="blong-test-run-page__picker"
                    disabled={busy}
                />
                <Button
                    type="button"
                    size="small"
                    icon="pi pi-play"
                    label={run ? 'Run again' : 'Run'}
                    disabled={!selectedMethod || busy}
                    onClick={() => void start()}
                />
                {busy && (
                    <Button
                        type="button"
                        size="small"
                        text
                        icon="pi pi-stop"
                        label="Stop"
                        onClick={stop}
                    />
                )}
                {error && (
                    <span
                        className="blong-test-run-page__error"
                        role="alert"
                    >
                        {error}
                    </span>
                )}
            </header>
            <div className="blong-test-run-page__console">
                {run ? (
                    <TestRun
                        run={run}
                        sourceLink={sourceLink}
                        defaultDetailsOpen={defaultDetailsOpen}
                    />
                ) : (
                    <div className="blong-test-run-page__empty">
                        <Text>Select a scenario and run it</Text>
                    </div>
                )}
            </div>
            {capture && run && (
                <pre
                    className="blong-test-run-page__model"
                    data-testid="test-run-model"
                    hidden
                >
                    {captureJson(run)}
                </pre>
            )}
            {capture && run && (
                <pre
                    className="blong-test-run-page__model"
                    data-testid="test-run-events"
                    hidden
                >
                    {captureJson(eventsRef.current)}
                </pre>
            )}
        </div>
    );
}