class: SpecterWorld

The SpecterWorld class provides methods to interact with the Unreal Engine instance. It is the primary fixture passed to every test, equivalent to the page fixture in Playwright.

Connection & Lifecycle

SpecterWorld.connect

Static factory method that connects to an Unreal Engine instance over WebSockets and returns a new SpecterWorld fixture.

Usage

const world = await SpecterWorld.connect();

Arguments

  • urlstring(optional)
    The WebSocket URL (Default: 'ws://127.0.0.1:8080').

Returns

world.joinHost

Commands the local client to join a multiplayer host/server via IP.

Usage

await world.joinHost("192.168.1.100", "Arena_P");

Arguments

  • ipAddressstring
    The server IP address.
  • expectedMapstring(optional)
    Wait for this map to load after joining.

Returns

  • Promise<void>

world.close

Closes the WebSocket connection to the engine.

Usage

await world.close();

Returns

  • Promise<void>

world.cleanup

Destroys all actors that were dynamically spawned during the test via world.spawnActor().

Usage

await world.cleanup();

Returns

  • Promise<void>

World & Level Management

world.loadMap

Synchronously loads a level. Supports advanced options like game modes and listen servers.

Usage

await world.loadMap("/Game/Maps/Arena", { listen: true });

Arguments

  • mapNamestring
    The map name or path.
  • optionsLoadMapOptions(optional)
    Configuration object.

Returns

  • Promise<void>

world.waitForMapLoad

Waits for a specific map to be loaded.

Usage

await world.waitForMapLoad("Arena");

Arguments

  • mapNamestring
    The map to wait for.
  • timeoutnumber(optional)
    Timeout in ms (Default: 15000).

Returns

  • Promise<void>

world.currentMap

Property getter for the currently loaded map name.

Usage

console.log(world.currentMap);

Returns

  • string

world.getNetworkStatus

Retrieves the current network mode and server address.

Usage

const status = await world.getNetworkStatus();

Returns

  • Promise<{ netMode: string, map: string, serverAddress: string }>

world.spawnActor

Synchronously spawns an actor of the given class into the world.

Usage

const boss = await world.spawnActor('/Game/Blueprints/Enemies/BP_Boss');

Arguments

  • assetPathstring
    The blueprint class path to spawn.
  • optionsSpawnOptions(optional)
    Configuration object containing location, rotation, and properties.

Returns

Global Engine Execution

world.evaluate

Executes a global C++ plugin command.

Usage

await world.evaluate("TakeScreenshot", { fileName: "menu" });

Arguments

  • commandNamestring
    The command to execute.
  • payloadobject(optional)
    Command payload.
  • contextstring(optional)
    Test runner UI context.
  • targetLocatorstring(optional)
    Target locator string.

Returns

  • Promise<any>

world.console

Executes a raw Unreal Engine console command.

Usage

await world.console("cheat god");

Arguments

  • commandStringstring
    The console command.

Returns

  • Promise<void>

world.setTimeScale

Adjusts the global time dilation of the Unreal Engine world. Alias for world.setTimeDilation(). Useful for fast-forwarding through long cutscenes or slowing down simulation to validate frame-perfect physics and combat.

Usage

// Fast-forward simulation at 2x speed
await world.setTimeScale(2.0);

Arguments

  • multipliernumber
    The time scale multiplier (1.0 is normal speed, 2.0 is 2x fast-forward, 0.5 is slow motion).

Returns

  • Promise<void>

world.setTimeDilation

Adjusts the global Unreal Engine time dilation (AWorldSettings::SetTimeDilation). Alias for world.setTimeScale(). Multiplier of 1.0 represents normal real-time speed, > 1.0 runs faster, and < 1.0 runs in slow motion.

Usage

// Slow down simulation to half speed for physics validation
await world.setTimeDilation(0.5);

Arguments

  • multipliernumber
    The time dilation multiplier (1.0 is normal speed, 2.0 is 2x fast-forward, 0.5 is slow motion).

Returns

  • Promise<void>

world.stepFrame

Advances the Unreal Engine simulation forward frame-by-frame. Essential for tick-accurate inspection, physics stepping, and deterministic playback verification.

Usage

// Advance simulation by 1 frame
await world.stepFrame(1);

// Step 5 frames during combat collision resolution
await world.stepFrame(5);

Arguments

  • frameCountnumber(optional)
    Number of frames to advance (Default: 1).

Returns

  • Promise<void>

world.advanceTime

Fast-forwards the Unreal Engine simulation time by the specified number of seconds without sleeping in real time. Skips cooldowns, buff durations, and timers in a fraction of a second.

Usage

// Fast-forward 60 in-game seconds in ~500ms of real time!
await world.advanceTime(60.0);
await expect(knightActor).not.toHaveGameplayTag("Cooldown.Abilities.R");

Arguments

  • secondsnumber
    Number of in-game seconds to fast-forward.

Returns

  • Promise<void>

world.waitForGameSeconds

Waits for a duration of in-game simulation seconds. Automatically scales the wall-clock wait time down based on the currently active time dilation (e.g. 5 seconds at 10x dilation takes 500ms).

Usage

// Waits for 5 in-game seconds (takes 500ms if timeDilation is 10.0)
await world.waitForGameSeconds(5.0);

Arguments

  • secondsnumber
    In-game seconds to wait.

Returns

  • Promise<void>

world.waitForTimeout

Pauses test execution for the specified duration in milliseconds. Prefer auto-retrying expect assertions when possible.

Usage

await world.waitForTimeout(1000); // Wait 1 second

Arguments

  • millisecondsnumber
    Duration to wait in milliseconds.

Returns

  • Promise<void>

world.takeScreenshot

Captures a screenshot of the active Unreal Engine viewport, with the UI, as the player sees it. Attaches it to the test's report and returns where it was saved. When a test fails, Specter takes one of these too, always with the UI.

Usage

const path = await world.takeScreenshot("inventory_open");

// Just the scene, without the HUD
await world.takeScreenshot("lighting_pass", { showUI: false });

Arguments

  • fileNamestring
    The name of the saved file.
  • optionsObject(optional)
    • showUIboolean(optional)Defaults to true
      Include the UMG UI layer. Set it to false to see just the scene.
    • attachmentNamestring(optional)
      The attachment's name in the report. Defaults to the file name.
    • attachboolean(optional)Defaults to true
      Attach the image to the test's report.

Returns

  • Promise<string>

world.waitForVariable

Pauses test execution until Unreal Engine pushes an instant telemetry event confirming that a tracked UPROPERTY variable has reached the expected value. Unlike polling, this is zero-overhead and event-driven. See the Events & Telemetry Guide for details.

Usage

const matchStateVar = await world.actor('GameStateBase').trackProperty('MatchState');

// Wait for game state to transition to in-progress
const event = await world.waitForVariable(matchStateVar, "InProgress");
console.log(`Match started at engine timestamp: ${event.timestamp}s`);

// Fast-forward or wait until Wave 5 with a custom 10s timeout
const waveVar = await world.actor('BP_WaveSpawner').trackProperty('CurrentWave');
await world.waitForVariable(waveVar, "5", 10000);

Arguments

  • varNamestring
    The stable variable string returned by a call to trackProperty() or trackAttribute().
  • expectedValuestring
    The expected stringified value to wait for (e.g. 'InProgress', '5', 'true').
  • timeoutnumber(optional)Defaults to 5000
    Maximum time in milliseconds to wait before failing with a timeout error.

Returns

world.waitForEvent

Natively waits for a C++ UObject delegate to broadcast on the world context (e.g. mapLoaded, playerJoined, actorSpawned). Supports predicate filtering.

Usage

// Custom timeout & predicate options
await world.waitForEvent('playerJoined', {
    timeout: 10000,
    predicate: (data) => data.playerName === 'Player_1'
});

Arguments

  • eventNamestring
    The name of the world event to bind to.
  • optionsOrPredicateFunction | Object(optional)
    A predicate function (payload) => boolean, or an options object { timeout, predicate }.

Returns

  • Promise<any>

Input Simulation

Methods for simulating hardware input globally across the active game viewport.

world.keyboard.press

Simulates a raw hardware key press globally.

Usage

// Option 1: Press and hold the key for 2000ms (2 seconds) before releasing
await world.keyboard.press('E', 2000);

Arguments

  • keystring
    The UE key name (e.g. 'E', 'SpaceBar').
  • holdMsnumber(optional)
    How long to hold the key before releasing it (in milliseconds).

Returns

  • Promise<void>

world.keyboard.down

Manually holds a key down indefinitely.

Usage

// Option 2: Manually hold the key down indefinitely (e.g., walking forward)
await world.keyboard.down('W');
await world.waitForEvent('SomeEvent'); // Wait for something to happen while walking
await world.keyboard.up('W'); // Release it

Arguments

  • keystring
    The UE key name.

Returns

  • Promise<void>

world.keyboard.up

Releases a manually held key.

Usage

await world.keyboard.up('W');

Arguments

  • keystring
    The UE key name.

Returns

  • Promise<void>

world.injectAxis

Injects a raw analog value directly into the PlayerController's InputAxis method. Useful for simulating fine analog movements like slightly tilting a gamepad thumbstick or partially pulling a trigger.

Usage

// Push the left thumbstick 50% forward for one frame
await world.injectAxis('Gamepad_LeftY', 0.5);

Arguments

  • axisNamestring
    The name of the axis binding (e.g. 'Gamepad_LeftY').
  • valuenumber
    The float value to inject (typically -1.0 to 1.0).

Returns

  • Promise<void>

world.playSequence

Plays a mathematically accurate frame-by-frame SpecterInputSequence applied globally to the engine's active game viewport.

Usage

import { SpecterInputSequence } from '@specter-automation/test';

const spinAttack = new SpecterInputSequence()
    .addAxisCircle('Gamepad_LeftX', 'Gamepad_LeftY', 0, 1500, 2);

await world.playSequence(spinAttack);

Arguments

  • sequenceSpecterInputSequence
    The input sequence to play.
  • optionsObject(optional)
    { loops?: number } The number of times to loop the sequence.

Returns

  • Promise<void>

Locator Factories

Methods for querying objects in the engine. These return lazy-evaluated Locators.

world.actor

Queries actors by Blueprint class name, or by Gameplay Tag using a 'Tag:' or 'tag=' prefix selector. When a class with exactly that name exists, only it and its subclasses match: 'BP_Enemy' doesn't match BP_EnemySpawner. A name that's only part of a class name still matches the classes that contain it.

Usage

// By Class Name (Default)
const player = world.actor("BP_Hero");

// By Gameplay Tag Prefix Selector (Playwright-style)
const boss = world.actor("Tag:Enemy.Boss");
const bossAlt = world.actor("tag=Enemy.Boss");

Arguments

  • selectorstring
    Class name (e.g. 'BP_Hero') or tag prefix selector (e.g. 'Tag:Enemy.Boss' or 'tag=Enemy.Boss').

world.actorByTag

Queries actors by their Gameplay Tag.

Usage

const enemy = world.actorByTag("Enemy.Boss");

Arguments

  • tagNamestring
    The tag name.

world.widget

Queries UMG widgets by their Blueprint class name.

Usage

const inventory = world.widget("WBP_Inventory");

Arguments

  • classNamestring
    The class name.

world.getByTestId

Finds UI by a name that stays the same when its words change: a UMG widget's name in the designer, the test id a hand-drawn HUD reports with FSpecterHUD, or a Slate widget's tag or Automation Driver id. Prefer it over getByText for UI whose text is localized or changes.

Usage

await world.getByTestId('PlayButton').click();
await expect(world.getByTestId('GameClock')).toBeVisible();

Arguments

  • testIdstring
    The widget's name or test id.
  • optionsObject(optional)
    { exact?: boolean } (default true).

world.getByPlayerId

Queries for the pawn of a specific player: the pawn whose PlayerState has that Player ID, or, when none does (a pawn with no PlayerState, or IDs that don't start at 0), the pawn of the Nth player controller. So getByPlayerId(0) is always the first player's pawn.

Usage

const p1 = world.getByPlayerId(0);

Arguments

  • playerIdnumber
    The player ID.

world.subsystem

Queries a UEngineSubsystem, UGameInstanceSubsystem, or ULocalPlayerSubsystem.

Usage

const audio = world.subsystem("AudioSubsystem");

Arguments

  • subsystemNamestring
    The subsystem class name.

world.uobject

Queries for a generic UObject in memory by its class name.

Usage

const saveGame = world.uobject("MySaveGame");

Arguments

  • classNamestring
    The object class name.

Performance Profiling

Real-time engine performance metrics for benchmarking and regression testing.

world.getPerformanceMetrics

Retrieves real-time performance metrics from the engine including FPS (from world delta time), frame time in ms, and used physical memory in MB.

Usage

const metrics = await world.getPerformanceMetrics();
console.log(`FPS: ${metrics.fps}`);
console.log(`Frame Time: ${metrics.frameTimeMs}ms`);
console.log(`Memory: ${metrics.memoryMb}MB`);

// Assert minimum performance threshold
expect(metrics.fps).toBeGreaterThan(30);

Returns

  • Promise<{ fps: number, frameTimeMs: number, memoryMb: number }>

world.measurePerformance

Records every frame while action runs and returns a capture: frame-time percentiles, FPS, game, render and GPU thread times, draw calls, memory, and each hitch with what happened in the game around it. Check it with the capture matchers. If the action throws, the capture still stops and is attached to the step before the error is rethrown. See Performance Testing.

Usage

const perf = await world.measurePerformance(async () => {
  await hero.triggerAbilityByTag('Ability.Slot.Q');
  await world.waitForTimeout(3000);
}, { name: 'Ability barrage' });

await expect(perf).toHaveFrameTimeP95Below(20);
await expect(perf).toHaveNoHitchesOver(50);

Arguments

  • action() => Promise<unknown>
    What to measure.
  • optionsMeasurePerformanceOptions(optional)
    { name?: string, hitchMs?: number (default 50), timelinePreview?: boolean (default true) }.

Returns

world.getMemory

How much physical memory the game uses now and at its peak since the test started (sampled four times a second), and how the texture streaming pool is doing: its size, and how far over budget the textures went. resetPeak starts the peak over from now. In the editor the numbers include the editor itself, so check budgets in a standalone or packaged game.

Usage

const memory = await world.getMemory();
console.log(memory.usedMB, memory.peakSinceTestMB, memory.textureStreaming.overBudgetMB);

Arguments

  • optionsObject(optional)
    { resetPeak?: boolean }.

Returns

  • Promise<MemoryStats>

Timeline Preview

Choose what the runner's timeline preview shows while this test runs. Every test starts on auto(), and a choice lasts until the test ends. When previews are off (in the Specter settings, or with no game view), these change nothing and return { recording: false }; they never fail a test.

world.preview.follow

Shows only these actors (a pawn, its AI controller or one of its components all mean the actor). Those close together share a view; far apart, each gets its own. An actor that's destroyed drops out, and when none are left the preview goes back to auto().

Usage

// A boss fight: keep the boss and the hero in view, wherever they go
await world.preview.follow([boss, hero]);
await world.preview.follow(adds, { add: true });

Arguments

  • actorsSpecterLocator | SpecterLocator[]
    The actors to keep in view.
  • optionsObject(optional)
    { add?: boolean } adds to the actors already followed instead of replacing them.

Returns

world.preview.at

Shows a fixed place: a sphere of radius (default 1500) around the location, from above at an angle.

Usage

// Watch a doorway, whoever comes through it
await world.preview.at({ x: 1200, y: -300, z: 0 }, { radius: 800 });

Arguments

  • locationVector3
    The point to look at.
  • optionsObject(optional)
    { radius?: number } in Unreal units (default 1500).

Returns

world.preview.player

Shows the player's view, as the game draws it (a first-person test, a menu).

Usage

await world.preview.player();

Returns

world.preview.auto

Back to following the action (or to the player's view, when Preview Follows the Action is off in the Specter settings).

Usage

await world.preview.auto();

Returns

AI & Navigation (Global)

Global NavMesh queries that are not tied to a specific actor.

world.isPointReachable

Runs a synchronous NavMesh path query via UNavigationSystemV1 to determine if a path exists between two world positions.

Usage

const reachable = await world.isPointReachable(
  { x: 100, y: 200, z: 0 },
  { x: 500, y: 600, z: 0 }
);
expect(reachable).toBe(true);

Arguments

  • startVector3
    The starting world coordinate.
  • endVector3
    The destination world coordinate.

Returns

  • Promise<boolean>

world.findNavPath

The navigation path from one place to another. Each end is a location or an actor (any locator). A path that stops short of the end counts as not found. The answer says why: the start or the end is off the navmesh, or how far short the path stops. To assert it, use toBeAbleToReach.

Usage

const path = await world.findNavPath(world.actor('PlayerStart_Red'), world.actor('Flag_Blue'));
// { found, partial, length, cost, areas: [{ area, polys, cost }], missedBy, fromOnNavMesh, toOnNavMesh, points? }
console.log(path.found, path.length);

Arguments

  • fromLocator | Vector3
    Where the path starts.
  • toLocator | Vector3
    Where it should lead.
  • optionsNavPathOptions(optional)
    { agent?: Locator (a pawn whose size picks the navmesh, and whose AI controller's query filter weighs the areas), filter?: string (a query filter class name or path), extent?: Vector3, points?: boolean (also return the path's points) }.

Returns

  • Promise<NavPath>

world.findNavPaths

Many paths in one call: one answer per { from, to } pair, in order. Use it to check every spawn against every objective without a round trip per pair.

Usage

const spawns = [world.actor('PlayerStart_Red'), world.actor('PlayerStart_Blue')];
const objectives = [world.actor('Flag_A'), world.actor('Flag_B')];
const { paths } = await world.findNavPaths(spawns.flatMap(from => objectives.map(to => ({ from, to }))));

Arguments

  • pairsArray<{ from, to }>
    Locators or locations.
  • optionsNavPathOptions(optional)
    As findNavPath.

Returns

  • Promise<{ paths: NavPath[], navData: string, building: boolean }>

world.waitForNavigation

Waits until the navmesh has finished (re)building: after the level loads, or after something changes it at runtime with dynamic navigation (a door, rubble, a destroyed wall).

Usage

await crate.setLocation(doorway);
await world.waitForNavigation();
await expect(world.actor('PlayerStart')).not.toBeAbleToReach(world.actor('Vault'));

Arguments

  • optionsObject(optional)
    { timeout?: number } in ms (default 10000).

Returns

  • Promise<void>

Sequencer & Cutscenes

Control and query Level Sequence (cutscene) playback state.

world.isSequencePlaying

Checks if a Level Sequence Actor is currently playing. Auto-discovers sequence by name match.

Usage

const playing = await world.isSequencePlaying('IntroSequence');

Arguments

  • sequenceNamestring
    The name of the Level Sequence Actor.

Returns

  • Promise<boolean>

world.getSequencePlaybackPosition

Returns current playback position of a Level Sequence in seconds.

Usage

const pos = await world.getSequencePlaybackPosition('IntroSequence');
console.log(`Cutscene is at ${pos}s`);

Arguments

  • sequenceNamestring
    The name of the Level Sequence Actor.

Returns

  • Promise<number>

world.scrubSequence

Scrubs the Level Sequence to an exact time position in seconds using EUpdatePositionMethod::Scrub.

Usage

// Jump to the 5-second mark of the intro cutscene
await world.scrubSequence('IntroSequence', 5.0);

// Verify the cutscene spawned a specific actor at that moment
await expect(world.actor('BP_CutsceneBoss')).toBeVisible();

Arguments

  • sequenceNamestring
    The name of the Level Sequence Actor.
  • positionSecondsnumber
    The target time position in seconds.

Returns

  • Promise<void>

Network & Lag Emulation

Methods available on world.network to simulate real-world multiplayer conditions.

world.network.setEmulatedLatency

Simulates network ping/latency on the active client connection.

Usage

await client1.network.setEmulatedLatency(150);

Arguments

  • pingMsnumber
    Target latency in milliseconds (e.g. 150).

Returns

  • Promise<void>

world.network.setPacketLoss

Simulates packet loss percentage on the active client network connection.

Usage

await client1.network.setPacketLoss(5);

Arguments

  • lossPercentnumber
    Packet loss percentage from 0 to 100 (e.g. 5).

Returns

  • Promise<void>

world.network.setLatencyVariance

Adds jitter to the emulated latency: each packet's delay varies by up to this many milliseconds.

Usage

await client1.network.setLatencyVariance(20);

Arguments

  • msnumber
    Latency variance in milliseconds (e.g. 20 for ±20 ms).

Returns

  • Promise<void>

world.network.resetEmulation

Resets emulated latency, jitter and packet loss back to 0.

Usage

await client1.network.resetEmulation();

Returns

  • Promise<void>

world.network.getStatus

The instance's net mode ('Standalone', 'Client', 'ListenServer' or 'DedicatedServer'), its map, and the server address it's connected to.

Usage

const { netMode } = await client1.network.getStatus();
expect(netMode).toBe('Client');

Returns

  • Promise<{ netMode: string; map: string; serverAddress: string }>

Match State & Players

The GameState's view of the match, from the server.

world.getMatchState

The match state from the GameState or GameMode, e.g. 'WaitingToStart', 'InProgress' or 'WaitingPostMatch'.

Usage

expect(await world.getMatchState()).toBe('InProgress');

Returns

  • Promise<string>

world.waitForMatchState

Waits until the match reaches a state (case-insensitive).

Usage

await world.waitForMatchState('InProgress', { timeout: 30000 });

Arguments

  • expectedStatestring
    The match state to wait for.
  • optionsObject(optional)
    { timeout?: number } in ms (default 10000).

Returns

  • Promise<void>

world.getPlayerCount

How many players the GameState lists (its PlayerArray).

Usage

expect(await server.getPlayerCount()).toBe(2);

Returns

  • Promise<number>

world.getServerWorldTime

The server's world time in seconds, as clients see it (GameState's GetServerWorldTimeSeconds).

Usage

const t = await client1.getServerWorldTime();

Returns

  • Promise<number>

world.restorePlayer

Gives the player's controller back the pawn, view target and camera rotation it had before the test possessed something else.

Usage

await world.restorePlayer();

Returns

  • Promise<void>

Level Streaming

Sub-levels and World Partition cells.

world.getStreamingLevels

Every streaming sub-level and World Partition cell with its state.

Usage

const levels = await world.getStreamingLevels();
console.table(levels.filter(l => l.isLoaded));

Returns

  • Promise<Array<{ levelName; packagePath; isLoaded; isVisible; isPending }>>

world.loadLevelStream

Starts streaming a sub-level in, and makes it visible once loaded (unless makeVisible is false). Follow it with waitForLevelVisible().

Usage

await world.loadLevelStream('SubLevel_BossRoom');
await world.waitForLevelVisible('SubLevel_BossRoom');

Arguments

  • levelNamestring
    The level's package name, e.g. 'SubLevel_BossRoom'.
  • makeVisibleboolean(optional)
    Default true.

Returns

  • Promise<void>

world.isLevelLoaded

Whether a sub-level or cell is loaded in memory.

Usage

await world.isLevelLoaded('SubLevel_BossRoom');

Arguments

  • levelNamestring
    The level's package name, e.g. 'SubLevel_BossRoom'.

Returns

  • Promise<boolean>

world.isLevelVisible

Whether a sub-level or cell is visible.

Usage

await world.isLevelVisible('SubLevel_BossRoom');

Arguments

  • levelNamestring
    The level's package name, e.g. 'SubLevel_BossRoom'.

Returns

  • Promise<boolean>

world.waitForLevelLoad

Waits until a sub-level or cell is loaded, for example after the player walks into its streaming range.

Usage

await world.waitForLevelLoad('SubLevel_BossRoom');

Arguments

  • levelNamestring
    The level's package name, e.g. 'SubLevel_BossRoom'.
  • optionsObject(optional)
    { timeout?: number } in ms (default 10000).

Returns

  • Promise<void>

world.getStreamingState

Whether streaming is done: no streaming level or World Partition cell loading or unloading. With at, whether the world around that place is loaded (World Partition), using the grid's own loading range or a radius.

Usage

const state = await world.getStreamingState({ at: { x: 120000, y: -45000, z: 0 } });
// { completed, completedAt, pending, pendingLevels, loaded, visible, worldPartition }

Arguments

  • optionsStreamingOptions(optional)
    { at?: Vector3, radius?: number (cm), state?: 'activated' (loaded and visible, the default) | 'loaded' }.

Returns

  • Promise<StreamingState>

world.waitForStreaming

Waits until streaming is done, everywhere or around at, and returns how long it took in seconds. For a time limit that fails the test, use toFinishStreaming.

Usage

await hero.setLocation(farCorner);
const seconds = await world.waitForStreaming({ at: farCorner });

Arguments

  • optionsStreamingOptions(optional)
    As getStreamingState, plus timeout?: number in ms (default 30000).

Returns

  • Promise<number>

world.waitForLevelVisible

Waits until a sub-level or cell is visible.

Usage

await world.waitForLevelVisible('SubLevel_BossRoom', { timeout: 20000 });

Arguments

  • levelNamestring
    The level's package name, e.g. 'SubLevel_BossRoom'.
  • optionsObject(optional)
    { timeout?: number } in ms (default 10000).

Returns

  • Promise<void>

Diagnostics & Traces

Debugging helpers. See also Debugging Tools.

world.getEngineLog

The engine's warnings and errors since the last test's cleanup: Blueprint runtime errors, failed attachments, missing assets, ensures. A line logged again is kept once with a count. Specter's own log lines are left out. The latest ones are also added to the diagnostics report when a GAS or AI matcher fails.

Usage

const { entries } = await world.getEngineLog();
expect(entries.filter((e) => e.verbosity === 'Error')).toEqual([]);

Arguments

  • optionsObject(optional)
    { max?: number } the most recent lines to return (default 100).

Returns

world.getStateHistory

Where the test's actors (what it spawned, and the pawns the game spawned while it ran) were and how they were doing, sampled four times a second: location, yaw, speed, health and their AI's path following. Times are seconds since the test started, the timeline's clock. It's also saved as state.json next to the test's timeline preview frames when the test ends.

Usage

const { sample } = await world.getStateHistory({ at: 6, actor: 'Minion' });
console.log(sample?.actors['BP_Minion_C_4']);
// { at: [2180, 35, 92], yaw: 4, speed: 0, health: 310, maxHealth: 400, move: 'Moving', moveGoal: [4000, 0] }

Arguments

  • optionsObject(optional)
    { from?: number, to?: number } a span of seconds; { at?: number } only the sample nearest then; { actor?: string } only actors whose name contains it.

Returns

world.getDiagnostics

A snapshot for debugging: a target actor's (and an instigator's) identity, attributes, tags, effects and abilities, how they stand towards each other, and recent flight-recorder events.

Usage

const report = await world.getDiagnostics({ target: enemy, instigator: hero });
console.log(report.relativeDirection, report.flightRecorder?.slice(-5));

Arguments

  • optionsObject(optional)
    { target?: ActorLocator, instigator?: ActorLocator, limit?: number } recent events (default 30).

Returns

  • Promise<SpecterDiagnosticsReport>

world.importTrace

Loads a saved .specter-trace file into the in-engine runner, with its steps, timeline events and matcher results, as if the test had just run there. Dropping the file on the runner does the same.

Usage

await world.importTrace('test-results/boss-fight/trace.specter-trace');

Arguments

  • traceFilePathstring
    Path to the .specter-trace file.

Returns

  • Promise<void>

Spatial Primitives & Visual Debugging

Draw persistent 3D spheres, bounding boxes, raycasts, and lines directly into the level viewport to visualize combat radiuses and collision tests.

world.drawDebugSphere

Draws a persistent 3D wireframe or solid sphere in world space to visualize AOE blast zones, capture areas, and explosion radii.

Usage

// AOE Blast / Capture Zone Sphere
await world.drawDebugSphere({
  center: { x: 0, y: 0, z: 92 },
  radius: 300,
  color: 'orange',
  duration: 8,
  thickness: 2
});

Arguments

  • optionsDebugSphereOptions
    Configuration object: { center: Vector3, radius: number, segments?: number, color?: string, duration?: number, thickness?: number }.

Returns

  • Promise<void>

world.drawDebugBox

Draws an oriented 3D bounding box in world space to visualize trigger volumes, spawn zones, and custom hitboxes.

Usage

// 3D Trigger Volume Box
await world.drawDebugBox({
  center: { x: 0, y: 300, z: 92 },
  extent: { x: 100, y: 100, z: 50 },
  color: 'magenta',
  duration: 8
});

Arguments

  • optionsDebugBoxOptions
    Configuration object: { center: Vector3, extent: Vector3, rotation?: Rotator, color?: string, duration?: number, thickness?: number }.

Returns

  • Promise<void>

world.drawDebugLine

Draws a 3D line trace or raycast between two world points to visualize projectile paths, line-of-sight checks, and trajectory traces.

Usage

// Line Trace / Raycast
await world.drawDebugLine({
  start: { x: -250, y: -200, z: 92 },
  end: { x: 0, y: 0, z: 92 },
  color: 'cyan',
  duration: 8,
  thickness: 3
});

Arguments

  • optionsDebugLineOptions
    Configuration object: { start: Vector3, end: Vector3, color?: string, duration?: number, thickness?: number }.

Returns

  • Promise<void>

world.clearDebugVisuals

Clears all active 3D debug shapes, spheres, boxes, lines, motion trails, and stats billboards across the entire level.

Usage

await world.clearDebugVisuals();

Returns

  • Promise<void>

Interfaces

DebugSphereOptions

interface DebugSphereOptions {
  center: Vector3;
  radius: number;
  segments?: number;
  color?: string;
  duration?: number;
  thickness?: number;
}

DebugBoxOptions

interface DebugBoxOptions {
  center: Vector3;
  extent: Vector3;
  rotation?: Rotator;
  color?: string;
  duration?: number;
  thickness?: number;
}

DebugLineOptions

interface DebugLineOptions {
  start: Vector3;
  end: Vector3;
  color?: string;
  duration?: number;
  thickness?: number;
}

SpawnOptions

interface SpawnOptions {
  tag?: string;
  location?: Vector3;
  rotation?: Rotator;
  properties?: Record<string, any>;
  spawnController?: boolean;
}

LoadMapOptions

interface LoadMapOptions {
  gameMode?: string;
  listen?: boolean;
}

TimelinePreviewState

interface TimelinePreviewState {
  recording: boolean;  // false: previews are off here, so the call changed nothing
  mode: string;        // "auto", "follow: BP_Boss_C_0, BP_Hero_C_1",
                       // "at (0, 2800, 90), radius 1500" or "player"
  note?: string;
}

PerformanceCapture

interface MeasurePerformanceOptions {
  name?: string;              // shown in the runner and failure messages
  hitchMs?: number;           // frames slower than this are hitches (default 50)
  timelinePreview?: boolean;  // keep recording preview frames (default true)
}

interface PerformanceCapture {
  name: string;
  durationSeconds: number;
  frameCount: number;
  frameTimeMs: { avg; p50; p90; p95; p99; max };   // milliseconds
  fps: { avg; onePercentLow; min };
  gameThreadMs: { avg; p95 };
  renderThreadMs: { avg; p95 };
  gpuMs: { avg; p95 };
  slateMs: { avg; p95 };           // UI tick (in the editor, the whole editor UI)
  gameThreadWaitMs: { avg; p95 };
  reported: { renderThread; gpu; drawCalls };  // false: the engine reported 0 throughout
  drawCalls: { avg; max };
  memoryMb: { start; peak; end; growth };
  hitchThresholdMs: number;
  hitchCount: number;
  hitches: PerformanceHitch[];     // slowest first, up to 50
}

interface PerformanceHitch {
  timeSeconds: number;   // into the capture
  testSeconds: number;   // on the test's timeline
  frameMs: number;
  bound: string;         // "Game thread", "GPU", "Slate UI", ... or "Unaccounted"
  events: string[];      // GC, level streaming, commands, steps around that frame
}

SpecterTimelineEvent

interface SpecterTimelineEvent {
  timestamp: number;        // Game world time in seconds
  eventName: string;        // The tracked UPROPERTY variable name
  description: string;      // Human-readable summary
  eventType: 'StandardVariable' | 'GameplayAttribute' | 'GameplayTag';
  oldValue: string;         // Previous value before transition
  newValue: string;         // Current value after transition
  instigator?: string;      // Actor or subsystem that triggered change
}

EngineLog

interface EngineLog {
  entries: {
    seconds: number;          // since the last test's cleanup (real time)
    verbosity: 'Warning' | 'Error';
    category: string;         // 'LogScript', 'PIE', ...
    message: string;
    count: number;            // times it was logged
  }[];
  dropped: number;            // different lines not kept once the buffer was full
}

StateHistory

interface StateHistory {
  interval: number;                    // seconds between samples (0.25)
  classes: Record<string, string>;     // each actor's class
  samples?: StateSample[];             // with from/to (or neither: all of them)
  sample?: StateSample;                // with at
}

interface StateSample {
  t: number;                           // seconds since the test started
  actors: Record<string, {
    at: [number, number, number];
    yaw: number;
    speed: number;
    health?: number;
    maxHealth?: number;
    move?: string;                     // its AI's path following: Idle, Waiting, Paused, Moving
    moveGoal?: [number, number];
    gone?: boolean;                    // destroyed by then
  }>;
}