On This Page

Testing

37 symbols from @neontechspace/fluxerly/testing

Functions#

createFixtures#

Create an independent fixture set whose ID sequence starts from the beginning

Use one set per test, or the fixtures property of a test client, when IDs must not depend on other tests

createFixtures(): Fixtures
Returns
Fixtures
import { createFixtures } from "@neontechspace/fluxerly/testing"
const fixtures = createFixtures()
export const command = fixtures.message({ content: "!ping" })
import { createFixtures } from "@neontechspace/fluxerly/testing"
const fixtures = createFixtures()
export const command = fixtures.message({ content: "!ping" })

createTestBot#

Create a test client that runs a bot written for runBot: Its events, ignoreBots setting, commands and setup callback, with the same handler contexts, delivery defaults and command router as runBot

Handlers and commands are registered at once, and ready runs setup before connecting, as runBot does, so a test drives the bot exactly as Fluxer would. The setup signal aborts when shutdown starts. It returns the controls of createTestClient plus say, and shutdown or await using cleans it up. Automatic gateway filtering sees the bot's handlers, commands and setup registrations, and emit rejects dispatches that list suppresses

createTestBot<
    F extends MessageFields | undefined = undefined,
    S extends Readonly<Record<string, unknown>>
        = Readonly<
            Record<
                string,
                | Readonly<
                      Record<string, CommandArgumentDescriptor>
                  >
                | undefined
            >
        >
>(options: TestBotOptions<F, S>): TestBot<SelectedMessage<F>>createTestBot<
  F extends
    | MessageFields | undefined
    = undefined,
  S extends Readonly<
    Record<string, unknown>
  >
    = Readonly<
      Record<
        string,
        | Readonly<
            Record<
              string,
              CommandArgumentDescriptor
            >
          >
        | undefined
      >
    >
>(
  options: TestBotOptions<F, S>
): TestBot<SelectedMessage<F>>

Parameters

options
TestBotOptions<F, S>

Invalid options throw ConfigurationError, as runBot does, and a commands register callback that throws throws its ApplicationError. A failed setup rejects ready with ApplicationError whose source is "runBot setup", and setup runs at most once however often ready is called. The runBot supervision of a stopped subscription does not apply in tests

import assert from "node:assert/strict"
import { createTestBot } from "@neontechspace/fluxerly/testing"

await using test = createTestBot({
    commands: { prefix: "!", commands: { ping: { execute: ({ reply }) => reply("Pong!") } } },
})
await test.ready()
// The test transport answers the reply with an echoed message, so no rest.respond fixture is needed
const replies = await test.say("!ping")
// Checked first, because a failed assertion and a failed cleanup together can hide the reason behind SuppressedError
assert.deepEqual(test.failures(), [])
assert.deepEqual(replies.map((message) => message.content), ["Pong!"])
import assert from "node:assert/strict"
import { createTestBot } from "@neontechspace/fluxerly/testing"

await using test = createTestBot({
    commands: { prefix: "!", commands: { ping: { execute: ({ reply }) => reply("Pong!") } } },
})
await test.ready()
// The test transport answers the reply with an echoed message, so no rest.respond fixture is needed
const replies = await test.say("!ping")
// Checked first, because a failed assertion and a failed cleanup together can hide the reason behind SuppressedError
assert.deepEqual(test.failures(), [])
assert.deepEqual(
    replies.map((message) => message.content),
    ["Pong!"],
)

createTestClient#

Create a real default-API client wired to an in-memory Fluxer for application tests

Creation opens no connection and starts no timers. Call ready to connect, and shutdown or await using to clean up. The gateway enforces gateway.ignoredEvents, so register handlers before ready when automatic filtering is enabled

createTestClient<
    F extends MessageFields | undefined = undefined
>(options?: TestClientOptions<F>): TestClient<SelectedMessage<F>>createTestClient<
  F extends
    | MessageFields | undefined
    = undefined
>(
  options?: TestClientOptions<F>
): TestClient<SelectedMessage<F>>

Parameters

options optional
TestClientOptions<F>

Invalid options throw ConfigurationError as createClient does, and supplying transport or instance also throws ConfigurationError because the test transport owns both. The hint for a misspelled key suggests the closest key a test client accepts

import { createTestClient } from "@neontechspace/fluxerly/testing"

export async function greetingTest() {
    await using test = createTestClient({ cache: { members: true } })
    const joined = test.client.waitFor("guildMemberAdd")
    await test.ready()
    test.emit("GUILD_MEMBER_ADD", test.fixtures.member())
    const member = await joined
    return member.isOk() && test.client.members.get(member.value) !== undefined
}
import { createTestClient } from "@neontechspace/fluxerly/testing"

export async function greetingTest() {
    await using test = createTestClient({ cache: { members: true } })
    const joined = test.client.waitFor("guildMemberAdd")
    await test.ready()
    test.emit("GUILD_MEMBER_ADD", test.fixtures.member())
    const member = await joined
    return member.isOk() && test.client.members.get(member.value) !== undefined
}

Variables#

fixtureToken#

A token-shaped value used by test clients by default

It is not a credential, and the fake transport never sends it anywhere

const fixtureToken: "fixture-only-not-a-credential"

fixtures#

A shared fixture set for quick payloads

Its ID sequence continues across every caller in the process, so prefer createFixtures or a test client's fixtures when a test compares exact message or role IDs

const fixtures: Fixtures
import { fixtures } from "@neontechspace/fluxerly/testing"
export const ping = fixtures.message({ content: "!ping" })
import { fixtures } from "@neontechspace/fluxerly/testing"
export const ping = fixtures.message({ content: "!ping" })

Classes#

TestTimeoutError
A test wait, such as TestRoute.next, idle or say, did not finish within the timeoutMs the test passed
UnhandledTestFailuresError
A test client shut down after application code failed without a handler, such as an event handler or command that threw or returned a failed Result

Interfaces#

Fixtures#

A set of wire payload builders sharing one deterministic ID sequence

Each builder returns a fresh object whose unspecified fields take sensible defaults linked to one default community, channel and author, so payloads from one set refer to each other without extra setup. IDs come from a counter over a fixed 2026-01-01 creation time, so the same calls in the same order always produce the same IDs and timestamps

interface Fixtures
ids#

The IDs that builders use by default: One community, one text channel, one human author and the test bot account

bot

The test bot account ID, reported in READY by test clients

string
channel

Default text channel ID for channel and message payloads, also the community's system channel

string
guild

Default guild ID for guild, channel, member, message and GUILD_CREATE payloads

string
user

Default human account ID for user, member and message author payloads, also the community owner

string

botUser#

Build the test bot account, the user that test clients report in READY

botUser(overrides?: WireOverrides<WireUser>): WireUserbotUser(
  overrides?:
    WireOverrides<WireUser>
): WireUser

Parameters

overrides optional
WireOverrides<WireUser>
Returns
WireUser

channel#

Build a community text channel, by default the default channel in the default community

channel(overrides?: WireOverrides<WireChannel>): WireChannelchannel(
  overrides?:
    WireOverrides<WireChannel>
): WireChannel

Parameters

overrides optional
WireOverrides<WireChannel>

forumChannel#

Build a forum channel with a new ID in the default community, without tags

Pass type 16 for a media channel, which then leaves out default_forum_layout as Fluxer does

forumChannel(
    overrides?: WireOverrides<WireForumChannel>
): WireForumChannelforumChannel(
  overrides?:
    WireOverrides<WireForumChannel>
): WireForumChannel

Parameters

overrides optional
WireOverrides<WireForumChannel>

guild#

Build a community record, by default the default community owned by the default author

guild(overrides?: WireOverrides<WireGuild>): WireGuildguild(
  overrides?:
    WireOverrides<WireGuild>
): WireGuild

Parameters

overrides optional
WireOverrides<WireGuild>
Returns
WireGuild

guildCreate#

Build a GUILD_CREATE body for the default community, as sent after READY once the session is running

By default it holds the everyone role, the default text channel and the bot's own membership with a full user. The startup burst after READY lists member users by ID only, so it differs: Override members to describe it

guildCreate(overrides?: WireGuildCreateOverrides): WireGuildCreateguildCreate(
  overrides?:
    WireGuildCreateOverrides
): WireGuildCreate

Parameters

overrides optional
WireGuildCreateOverrides

member#

Build a membership of the default author in the default community, carrying guild_id as member events do

member(overrides?: WireOverrides<WireMember>): WireMembermember(
  overrides?:
    WireOverrides<WireMember>
): WireMember

Parameters

overrides optional
WireOverrides<WireMember>
Returns
WireMember

message#

Build a message with a new ID from the default author in the default channel and community

message(overrides?: WireOverrides<WireMessage>): WireMessagemessage(
  overrides?:
    WireOverrides<WireMessage>
): WireMessage

Parameters

overrides optional
WireOverrides<WireMessage>

nextId#

Return the next unused snowflake ID from this set's sequence

Each call returns a new, larger ID

nextId(): string
Returns
string

role#

Build a role with a new ID in the default community's role list, without permissions

role(overrides?: WireOverrides<WireRole>): WireRolerole(
  overrides?:
    WireOverrides<WireRole>
): WireRole

Parameters

overrides optional
WireOverrides<WireRole>
Returns
WireRole

thread#

Build a public thread with a new ID in the default channel, started by the default author, active and without the bot's membership

Pass type 12 for a private thread, whose default metadata then includes invitable, or a member field to describe the bot's membership

thread(overrides?: WireOverrides<WireThread>): WireThreadthread(
  overrides?:
    WireOverrides<WireThread>
): WireThread

Parameters

overrides optional
WireOverrides<WireThread>
Returns
WireThread

user#

Build a human account, by default the default author

user(overrides?: WireOverrides<WireUser>): WireUseruser(
  overrides?:
    WireOverrides<WireUser>
): WireUser

Parameters

overrides optional
WireOverrides<WireUser>
Returns
WireUser

TestBot#

A test client running a bot written for runBot, with say to talk to the bot as a user would

interface TestBot<M extends MessageCore = Message>
    extends TestClient<M>interface TestBot<
  M extends MessageCore = Message
>
  extends TestClient<M>

say#

Deliver a message with this content from a human user, wait until the bot has settled as idle does, and resolve with the messages the bot sent meanwhile, in send order, or an empty list when it sent nothing

Call ready first. Each entry is a message send (POST /channels/:id/messages) in wire shape, built from the request body with the fields the automatic reply echoes, so it shows what the bot sent even when a rest.respond handler answered, including a send that handler rejected

Edits, reactions and other requests are not included, and remain visible through requests(). The message comes from the fixture set's default human author in its default channel and community, and options.message replaces any of those wire fields

The content is normalized as Fluxer normalizes sent text, without form feed (U+000C) or U+202E and with surrounding whitespace trimmed, so "!ping " arrives as "!ping". Use emit with fixtures.message to deliver content unchanged

With the manual clock, say also resolves once the bot can continue only when the clock moves, as advance does at each stop, such as a command awaiting waitFor. Call advance next to let it finish, and inspect the later replies with requests()

Like idle, say has no deadline unless options.timeoutMs is set, then rejects with TestTimeoutError when the bot is still busy after it, and rejects with ClientClosedError after shutdown. It throws ConfigurationError for content that is not a string, invalid options, before ready and when gateway filtering would suppress the message, as emit does

say(
    content: string,
    options?: TestSayOptions
): Promise<readonly WireMessage[]>say(
  content: string,
  options?: TestSayOptions
): Promise<readonly WireMessage[]>

Parameters

content
string
options optional
TestSayOptions
Returns
Promise<readonly WireMessage[]>
import assert from "node:assert/strict"
import { createTestBot } from "@neontechspace/fluxerly/testing"

await using test = createTestBot({
    commands: { prefix: "!", commands: { ping: { execute: ({ reply }) => reply("Pong!") } } },
})
await test.ready()
const [reply] = await test.say("!ping")
// Checked first, because a failed assertion and a failed cleanup together can hide the reason behind SuppressedError
assert.deepEqual(test.failures(), [])
assert.equal(reply?.content, "Pong!")
assert.deepEqual(await test.say("hello"), [])
import assert from "node:assert/strict"
import { createTestBot } from "@neontechspace/fluxerly/testing"

await using test = createTestBot({
    commands: { prefix: "!", commands: { ping: { execute: ({ reply }) => reply("Pong!") } } },
})
await test.ready()
const [reply] = await test.say("!ping")
// Checked first, because a failed assertion and a failed cleanup together can hide the reason behind SuppressedError
assert.deepEqual(test.failures(), [])
assert.equal(reply?.content, "Pong!")
assert.deepEqual(await test.say("hello"), [])

Inherited from TestClient: client, fixtures, rest, advance, commands, counters, disconnect, emit, emitGatewayError, failures, idle, logs, ready, requests, shutdown

TestClient#

A real default-API client connected to an in-memory Fluxer, with controls for driving and inspecting it

Controls throw ConfigurationError for misuse, such as emitting before ready, and ClientClosedError after shutdown

interface TestClient<M extends MessageCore = Message>
    extends AsyncDisposableinterface TestClient<
  M extends MessageCore = Message
>
  extends AsyncDisposable
client#

The client under test, created with createClient

Use it exactly as in the application

Client<M>
fixtures#

A fixture set of its own, whose IDs do not depend on other tests

READY reports its botUser() by default

Fixtures
rest#

Register the HTTP responses the fake Fluxer API returns

TestRest

advance#

Move the manual test clock forward by ms milliseconds, then resolve once the client has settled at the new time

The clock stops at each SDK deadline on the way, in order, and waits there until the work it starts has settled, as idle does, before it moves on. So a task scheduled with delayMs runs once the clock reaches its delay, and an interval task advanced by three intervals runs three times

Calls made while one runs wait for it

Work that keeps running counts as waiting for the clock, so it cannot hold the clock still, only while every running handler, command and scheduled task awaits an SDK call, such as waitFor or a request in a rate limit wait, and nothing new happens for a few more event loop turns

A handler awaiting anything else, such as its own file, database or timer, is waited for as idle waits for it, before the clock moves on. A handler awaiting its own work and an SDK call together, as in Promise.all, counts as waiting for the clock

Like idle, it has no deadline, so work that keeps making requests or never finishes keeps it waiting. Throws ConfigurationError without clock: "manual" and for a negative or non-finite ms, and rejects with ClientClosedError after shutdown

advance(ms: number): Promise<void>

Parameters

ms
number
Returns
Promise<void>
import assert from "node:assert/strict"
import { createTestClient } from "@neontechspace/fluxerly/testing"

await using test = createTestClient({ clock: "manual" })
let runs = 0
test.client.schedule(() => void runs++, { delayMs: 60_000, intervalMs: 60_000 })
await test.advance(59_999)
assert.equal(runs, 0)
await test.advance(120_001)
assert.equal(runs, 3)
import assert from "node:assert/strict"
import { createTestClient } from "@neontechspace/fluxerly/testing"

await using test = createTestClient({ clock: "manual" })
let runs = 0
test.client.schedule(() => void runs++, { delayMs: 60_000, intervalMs: 60_000 })
await test.advance(59_999)
assert.equal(runs, 0)
await test.advance(120_001)
assert.equal(runs, 3)

commands#

Gateway commands the client sent so far, in order, with tokens redacted

commands(): readonly TestGatewayCommand[]
Returns
readonly TestGatewayCommand[]

counters#

The client's running totals, the same as client.diagnostics().counters

counters(): ClientCounters

disconnect#

Close one shard's connection from the gateway side with a close code

The SDK then recovers as it would against Fluxer, resuming with RESUMED for a resumable code, or ends the connection lifetime for a fatal one. With endSession set, the client identifies a new session instead of resuming. Throws ConfigurationError when that shard is not connected

disconnect(options?: TestDisconnectOptions): voiddisconnect(
  options?: TestDisconnectOptions
): void

Parameters

options optional
TestDisconnectOptions

emit#

Deliver one gateway dispatch to a connected shard synchronously, with the next sequence number

The type is the Fluxer wire dispatch name, such as MESSAGE_CREATE or GUILD_MEMBER_ADD, and the payload is the wire body in snake_case, so it passes through the SDK's real decoders, cache updates and handlers. With the client's cache option enabled, handlers receive EventContext.previous exactly as against Fluxer, and every accepted dispatch advances client.lastReceipt

Handlers run afterwards on their own schedule. Register client.waitFor before emitting to await delivery. Unknown types are delivered too unless explicitly suppressed, and malformed payloads follow the client's gateway.onMalformedDispatch policy. Throws ConfigurationError without consuming a sequence when the session's Identify filtering would suppress the dispatch

Suppressed MESSAGE_CREATE still arrives for a direct bot mention, @here or @everyone. Role-only mentions, direct-message delivery and bot authorship alone do not exempt it. Generated MESSAGE_REACTION_ADD_MANY is gated by MESSAGE_REACTION_ADD, not its generated name

Register handlers before ready when gateway.ignoredEvents is "auto", or remove the source type from the explicit list (use [] to disable suppression). Resume keeps the current list. READY and RESUMED are reserved for the handshake. Throws ConfigurationError before ready or for a shard this client does not own

emit(
    type: string,
    payload: unknown,
    options?: TestEmitOptions
): voidemit(
  type: string,
  payload: unknown,
  options?: TestEmitOptions
): void

Parameters

type
string
payload
unknown
options optional
TestEmitOptions

emitGatewayError#

Deliver one opcode 12 Gateway Error frame to a connected shard synchronously, as Fluxer does when it refuses a voice join

The data is the frame's d with Fluxer's field names, such as { code: "VOICE_CHANNEL_FULL", message: "Voice channel is full" }, and reaches gatewayError subscriptions, never raw ones, without a sequence number. The frame goes to shard 0 unless options.shardId names another shard. Handlers run afterwards on their own schedule. Throws ConfigurationError before ready, for a shard this client does not own and for data that is not JSON-serializable

emitGatewayError(
    data: GatewayErrorData,
    options?: TestEmitOptions
): voidemitGatewayError(
  data: GatewayErrorData,
  options?: TestEmitOptions
): void

Parameters

options optional
TestEmitOptions

failures#

Error records of failures no application code handled so far, in order, such as an event handler, command or client.schedule task run that threw or returned a failed Result while no onError hook was registered, whether the error came from the application or from a Fluxer rejection

Assert expected failures here, because shutdown rejects for unhandled failures that failures() has not returned. Failures are captured whatever the logging level, categories and deduplication, so each one appears here and counts for shutdown even when logs() leaves it out

failures(): readonly LogRecord[]
Returns
readonly LogRecord[]

idle#

Resolve once the client has settled: No event handler or command is running or has a received event waiting for it, no client.schedule task run is running, no REST request is queued or waiting for its test response, and no new log record, request or gateway command appeared for a few event loop turns

Use it after emit to assert that the bot did nothing, or before inspecting results. Open waits and collectors do not count as work, and onError hooks are not awaited

A scheduled task waiting for its time does not count either, so advance the manual clock to run it, or wait for its delay on real time. Without timeoutMs the wait has no SDK deadline, so it can run forever unless the test runner stops the test

With timeoutMs the promise rejects with TestTimeoutError when the client is still busy after it. It rejects with ClientClosedError after shutdown. Invalid options throw ConfigurationError. The wait's own timers, including timeoutMs, stay real when a test fakes timers

The SDK runs on setImmediate, so fake timers must leave it real, otherwise idle rejects with ConfigurationError instead of settling while no handler can run

idle(options?: TestWaitOptions): Promise<void>idle(
  options?: TestWaitOptions
): Promise<void>

Parameters

options optional
TestWaitOptions
Returns
Promise<void>

logs#

Log records the client produced so far, in order, at the logging option's level and categories, default Info

The records also reach any sinks in the logging option. Nothing is printed to the console

logs(): readonly LogRecord[]
Returns
readonly LogRecord[]

ready#

Connect the client to the test gateway and resolve once every shard it owns is READY, like client.connect

Calling it again while connected resolves without opening another socket. With gateway.ignoredEvents set to "auto", register handlers before this call, because Identify chooses the session's filtering from those registrations. The promise rejects with the connect failure, such as ConnectionError when a handler closed the connection, so a failed start fails the test

ready(options?: OperationOptions): Promise<void>ready(
  options?: OperationOptions
): Promise<void>

Parameters

options optional
OperationOptions
Returns
Promise<void>

requests#

HTTP requests the client sent so far, in order, excluding the discovery bootstrap and without credentials

requests(): readonly TestRequest[]
Returns
readonly TestRequest[]

shutdown#

Shut the client down, then close the test transport

Resolves after both finish and can be called again. Rejects with SdkDefect when client cleanup fails, and otherwise with UnhandledTestFailuresError when application code failed without a handler and failures() did not return that failure, so a broken handler fails the test. Each failure is reported once, so a later call resolves. Disposal with await using calls it

shutdown(): Promise<void>
Returns
Promise<void>

TestClockSettings#

Choose the clock that a default test client's SDK timers follow

interface TestClockSettings
clock optional#

The clock of the SDK's own timers, default "real"

With "manual", a test clock that starts at 0, as monotonic time and as Unix epoch milliseconds, moves only when advance moves it

It drives client.schedule delays and intervals, waitFor and collector timeouts, cooldowns in a command router's own store, cache expiry, member request timeouts, REST and presence pacing, the keepTyping refresh, reconnect delays and the gateway heartbeat. A cooldown store passed to a command, such as commands.memoryCooldowns(), keeps its own time

Date.now() and new Date() in application code, timers the application starts itself, the timeoutMs of next, idle and say, and socket and process watchdogs keep real time

A client that owns more than one shard or uses automatic sharding throws ConfigurationError with "manual", because the SDK spaces several shards' Identify commands on the clock, and so does any other value

"manual" | "real"

TestDisconnectOptions#

Choose how the test gateway ends one shard's connection

interface TestDisconnectOptions
code optional#

WebSocket or gateway close code the client receives, default 4000 (unknown error), after which the SDK reconnects and resumes

Every recoverable code resumes the same session, including 4007 (invalid sequence), so the shard's sessionEpoch stays the same. Use endSession to start a new session. A fatal code such as 4004 ends the client's connection lifetime instead

number
endSession optional#

Whether the test gateway forgets the shard's session before it closes the connection, default false

The client's Resume then gets Invalid Session, as when Fluxer no longer holds the session, so the client identifies a new session. The shard's sessionEpoch increases, the next event's context shows the higher value, and the SDK runs the same cache release and new-session handling as after a real session loss. A value that is not a boolean throws ConfigurationError. A fatal code still ends the client's connection lifetime, so combine this option with a recoverable code

boolean
shardId optional#

Local shard ID whose connection closes, default 0

number

TestEmitOptions#

Choose the shard that receives an emitted dispatch or Gateway Error frame

interface TestEmitOptions
shardId optional#

Local shard ID that receives the dispatch or Gateway Error frame

By default a payload with a guild_id, or a guild create, update or delete payload, goes to the shard Fluxer routes that community to, (guild_id >> 22) % totalShards, and any other payload goes to shard 0, which receives direct-message traffic. A Gateway Error frame goes to shard 0

number

TestGatewayCommand#

One gateway command a client sent to the test gateway, in send order

Identify and Resume carry "[redacted]" in place of the token

interface TestGatewayCommand
d#

Command data as sent, parsed from JSON

unknown
op#

Gateway opcode, such as 2 for Identify, 3 for Presence Update or 8 for Request Guild Members

number
shardId#

Shard that sent the command, or null when it came before the socket identified or resumed

number | null

TestRequest#

One HTTP request a test client sent, as recorded by the test transport and passed to response handlers

The record never contains the Authorization header, and a webhook token in the path reads "[redacted]"

interface TestRequest
body#

Request body: Parsed JSON for JSON requests, the parsed payload_json part of a multipart upload, the text of any other body, or undefined when the request has none

unknown
files#

Attachment parts of a multipart upload, empty for other requests

readonly TestRequestFile[]
headers#

Request headers with lower-case names, without authorization

Readonly<Record<string, string>>
matched#

Whether a registered response answered the request

False means the test transport answered it itself, with the automatic reply to a message send or edit, or otherwise with the default 404

boolean
method#

Upper-case HTTP method

string
path#

Fluxer API path after the /v1 prefix and without the query string, such as /channels/1/messages

Requests to other origins, such as media downloads, use the absolute URL without its query string

string
query#

Query parameters

A repeated parameter keeps its last value

Readonly<Record<string, string>>
url#

Absolute request URL, including the query string

string

TestRequestFile#

One attachment part of a recorded multipart request

interface TestRequestFile
contentType#

Declared content type

string
field#

Form field name, such as files[0]

string
filename#

Uploaded file name

string
size#

Size in bytes

number

TestRest#

Register fake Fluxer HTTP API responses for a test client

Without a registration, message sends (POST /channels/:id/messages) and edits (PATCH /channels/:id/messages/:id) receive an automatic reply: A message by the bot account that echoes the request's content, embeds, flags and tts, with a new fixture ID for a send and the edited ID for an edit. Other unmatched requests receive a Fluxer-shaped 404. The echoed content is normalized as Fluxer stores it, without form feed (U+000C) or U+202E and with surrounding whitespace trimmed

interface TestRest

respond#

Answer matching requests with a fixed response or a handler's response until the registration is removed

The newest matching registration wins, including over the automatic message replies. Invalid matchers or responses throw ConfigurationError

respond(
    matcher: TestRequestMatcher,
    response: TestResponse | TestResponder
): TestRouterespond(
  matcher: TestRequestMatcher,
  response:
    | TestResponse | TestResponder
): TestRoute

Parameters

Returns
TestRoute
import { createTestClient } from "@neontechspace/fluxerly/testing"
export function respondExample() {
    const test = createTestClient()
    test.rest.respond("GET /users/@me", { body: test.fixtures.botUser() })
    return test.rest.respond("POST /channels/:id/messages", (request) => ({
        body: test.fixtures.message({ content: String(request.body.content) }),
    }))
}
import { createTestClient } from "@neontechspace/fluxerly/testing"
export function respondExample() {
    const test = createTestClient()
    test.rest.respond("GET /users/@me", { body: test.fixtures.botUser() })
    return test.rest.respond("POST /channels/:id/messages", (request) => ({
        body: test.fixtures.message({ content: String((request.body as { content?: unknown }).content) }),
    }))
}

TestRoute#

One registered response

Registrations are searched newest first, so a later registration overrides an earlier one for the requests both match

interface TestRoute

next#

Resolve with the next request this registration answers

Each call returns a different request, in order, so a request that arrived before the call is returned at once. Without timeoutMs the wait has no SDK deadline, so it can run forever unless the test runner stops the test. With timeoutMs the promise rejects with TestTimeoutError when no request arrives in time. It rejects with ClientClosedError when the test client shuts down first. Invalid options throw ConfigurationError

next(options?: TestWaitOptions): Promise<TestRequest>next(
  options?: TestWaitOptions
): Promise<TestRequest>

Parameters

options optional
TestWaitOptions
Returns
Promise<TestRequest>

remove#

Stop answering requests

Earlier matching registrations apply again. Without a match, message sends and edits receive automatic message replies, and other requests receive the default 404

remove(): void

requests#

Requests this registration answered so far, in order

requests(): readonly TestRequest[]
Returns
readonly TestRequest[]

TestSettings#

Settings that only test clients accept, alongside the usual client options

interface TestSettings
heartbeatIntervalMs optional#

Heartbeat interval in milliseconds sent in HELLO, default 41,250 as on hosted Fluxer

The client heartbeats on its own timer, which shutdown stops

number
token optional#

Token passed to the client, default the fixture token

The fake transport never sends it anywhere

string
user optional#

Bot account the test gateway reports in READY, default the test client's fixtures.botUser()

WireUser

TestWaitOptions#

Limit how long a test wait, such as TestRoute.next, idle or say, may take

interface TestWaitOptions
timeoutMs optional#

Milliseconds before the wait fails with TestTimeoutError, an integer from 1 through 2,147,483,647

Omit it to wait without an SDK deadline, which can run forever unless the test runner stops the test. The timeout uses real timers, so it still fires when a test fakes timers. Any other key, such as a misspelled timeoutMs, throws ConfigurationError

number

WireChannel#

A community channel in the wire shape of channel reads and channel events

interface WireChannel
guild_id#

Guild ID

Private channels omit it

string
id#

Channel snowflake ID

string
last_message_id#

Latest message ID, or null when none is known

string | null
last_pin_timestamp#

Latest pin time, or null when nothing is pinned

string | null
name#

Channel name

string
nsfw#

Whether the channel is marked NSFW

boolean
parent_id#

Parent category ID, or null when uncategorized

string | null
permission_overwrites#

Role and member permission overwrites

readonly unknown[]
position#

Sorting position

number
rate_limit_per_user#

Slow-mode interval in seconds

number
topic#

Topic, or null when unset

string | null
type#

Channel type, 0 for a text channel

number

WireForumChannel#

A forum or media channel in the wire shape of channel reads and channel events

interface WireForumChannel
available_tags#

Tags that posts can carry

readonly {
    readonly emoji_id: string | null
    readonly emoji_name: string | null
    readonly id: string
    readonly moderated: boolean
    readonly name: string
}[]readonly {
  readonly emoji_id: string | null
  readonly emoji_name: string | null
  readonly id: string
  readonly moderated: boolean
  readonly name: string
}[]
default_auto_archive_duration#

Stored default auto-archive period in minutes, or null when unset

number | null
default_forum_layout optional#

Default post layout, present only on a forum channel

number
default_reaction_emoji#

Reaction suggested on each post, or null when unset

| {
      readonly emoji_id: string | null
      readonly emoji_name: string | null
  }
| null| {
    readonly emoji_id: string | null
    readonly emoji_name: string | null
  }
| null
default_sort_order#

Default post order, or null when unset

number | null
default_tag_setting#

Default tag matching of a post search

string
default_thread_rate_limit_per_user#

Slow-mode interval in seconds that new posts copy

number
flags#

Channel flag bits, where 16 requires a tag on every post

number
guild_id#

Guild ID

string
id#

Channel snowflake ID

string
last_message_id#

Newest post ID, or null when the channel never had one

string | null
last_pin_timestamp#

Latest pin time, or null

string | null
name#

Channel name

string
nsfw#

Whether the channel is marked NSFW

boolean
parent_id#

Parent category ID, or null when uncategorized

string | null
permission_overwrites#

Role and member permission overwrites

readonly unknown[]
position#

Sorting position

number
rate_limit_per_user#

Delay in seconds between one member's posts

number
topic#

Posting guidelines, or null when unset

string | null
type#

Channel type, 15 for a forum channel or 16 for a media channel

number

WireGuild#

A community record in the wire shape of guild reads, GUILD_UPDATE and the properties of GUILD_CREATE

interface WireGuild
afk_channel_id#

AFK voice channel ID, or null when unset

string | null
afk_timeout#

AFK timeout in seconds

number
banner#

Banner hash, or null when unset

string | null
content_warning_level#

Content warning level

number
content_warning_text#

Content warning text, or null when unset

string | null
default_message_notifications#

Default notification level

number
disabled_operations#

Disabled community operation bits

number
embed_splash#

Embed splash hash, or null when unset

string | null
explicit_content_filter#

Explicit content filter level

number
features#

Enabled community feature names

readonly string[]
icon#

Icon hash, or null when unset

string | null
id#
string
mfa_level#

MFA requirement level

number
name#

Community name

string
nsfw#

Whether the community is marked NSFW

boolean
nsfw_level#

NSFW classification level

number
owner_id#

Owner account ID

string
rules_channel_id#

Rules channel ID, or null when unset

string | null
splash#

Invite splash hash, or null when unset

string | null
splash_card_alignment#

Splash card alignment, 0 for center

number
system_channel_flags#

System channel flag bits

number
system_channel_id#

System message channel ID, or null when unset

string | null
vanity_url_code#

Vanity invite code, or null when unset

string | null
verification_level#

Verification level

number

WireGuildCreate#

A complete GUILD_CREATE dispatch body: The community ready object with its roles, channels, threads and members

interface WireGuildCreate
channels#

Channels the bot can view, including forum and media channels

readonly (WireChannel | WireForumChannel)[]readonly (
  | WireChannel | WireForumChannel)[]
emojis#

Community emojis

readonly unknown[]
id#

Guild snowflake ID, equal to properties.id

string
joined_at#

ISO 8601 time the bot joined, or null

string | null
member_count#

Total member count

number
members#

Members sent with the community, without guild_id

readonly unknown[]
online_count#

Online member count

number
presences#

Always empty

Presences arrive as separate dispatches

readonly unknown[]
properties#

The community record

WireGuild
roles#

Every role, including the everyone role

readonly WireRole[]
stickers#

Community stickers

readonly unknown[]
threads#

Active threads the bot can view, each with member when the bot joined it

readonly WireThread[]
unavailable optional#

False in the startup burst after READY

Leave it out to describe a community the bot has just joined

boolean
voice_states#

Voice states in visible channels

readonly unknown[]

WireMember#

A community membership in the wire shape of GUILD_MEMBER_ADD and GUILD_MEMBER_UPDATE

Member reads return the same fields without guild_id, and the SDK ignores that extra field there

interface WireMember
accent_color#

Community profile accent color, or null when unset

number | null
avatar#

Community avatar hash, or null when unset

string | null
banner#

Community banner hash, or null when unset

string | null
communication_disabled_until#

ISO 8601 end of a timeout, or null when not timed out

string | null
deaf#

Whether the member is community-deafened

boolean
guild_id#

Guild ID carried by member events

string
joined_at#

ISO 8601 join time

string
mute#

Whether the member is community-muted

boolean
nick#

Community nickname, or null when unset

string | null
roles#

Assigned role IDs, excluding the everyone role

readonly string[]
user#

Member account

WireUser

WireMessage#

A message in the wire shape of message reads, MESSAGE_CREATE and MESSAGE_UPDATE

interface WireMessage
attachments#

Attachments

readonly unknown[]
author#

Message author

WireUser
channel_id#

Channel ID

string
channel_type optional#

Fluxer's numeric type of the channel, which only MESSAGE_CREATE carries

The default message has none, so pass 0 for a community text channel, 1 for a direct message or 3 for a group direct message to emit a created message in full

number
content#

Text content

string
edited_timestamp#

ISO 8601 edit time, or null when never edited

string | null
embeds#

Rich embeds

readonly unknown[]
flags#

Message flag bits

number
guild_id optional#

Guild ID

Direct messages omit it

string
id#

Message snowflake ID

string
member optional#

The author's community membership as MESSAGE_CREATE and MESSAGE_UPDATE carry it, without a user and guild ID because the author and guild_id of the message supply them

The default message has none, so pass the result of fixtures.member() without its user and guild_id to emit a decorated event. REST reads never carry it

Omit<WireMember, "user" | "guild_id">
mention_everyone#

Whether the message mentions everyone

boolean
mention_here optional#

Whether the message mentions here, which only MESSAGE_CREATE carries and Fluxer sends only as true

boolean
mention_roles#

Mentioned role IDs

readonly string[]
mentions#

Mentioned accounts

readonly WireUser[]
nicks optional#

Group direct message nicknames keyed by user ID, which only MESSAGE_CREATE carries and Fluxer omits when empty

Readonly<Record<string, string>>
pinned#

Whether the message is pinned

boolean
stickers#

Stickers

readonly unknown[]
timestamp#

ISO 8601 creation time

string
tts#

Whether the message was sent as text-to-speech

boolean
type#

Message type, 0 for a default message

number

WireRole#

A community role in the wire shape of role reads and role events

interface WireRole
color#

RGB color as an integer, 0 for none

number
hoist#

Whether members are shown separately

boolean
hoist_position#

Member-list hoist position, or null when unset

number | null
icon#

Image icon hash, or null when the role has no image icon

string | null
id#

Role snowflake ID

The everyone role uses the guild ID

string
mentionable#

Whether anyone may mention the role

boolean
name#

Role name

string
permissions#

Permission bits as a decimal string

string
position#

Position in the role list

number
unicode_emoji#

Unicode emoji shown with the role, or null when unset

string | null

WireThread#

A thread in the wire shape of thread reads, thread lists and THREAD_CREATE and THREAD_UPDATE

interface WireThread
applied_tags optional#

IDs of the tags applied to a forum or media post

readonly string[]
flags#

Channel flag bits, where 2 pins a forum post

number
guild_id#

Guild ID

string
id#

Thread snowflake ID

string
last_message_id#

Latest message ID, or null when the thread has none

string | null
last_pin_timestamp#

Latest pin time, or null when nothing was pinned

string | null
member optional#

The bot's own membership, present when the bot joined the thread

flags

Thread member flag bits

number
join_timestamp

ISO 8601 time the bot last joined

string
member_count#

Thread member count, capped at 50

number
message_count#

Messages in the thread

number
name#

Thread name

string
owner_id#

ID of the user or webhook that created the thread

string
parent_id#

ID of the text, announcement, forum or media channel holding the thread

string
rate_limit_per_user#

Slow-mode interval in seconds

number
thread_metadata#

Archive and lock state

archive_timestamp

ISO 8601 time the archive state last changed

string
archived

Whether the thread is archived

boolean
auto_archive_duration

Inactivity period in minutes before Fluxer archives the thread

number
create_timestamp

ISO 8601 creation time

string
invitable optional

Whether members may invite others, present only on a private thread

boolean
locked

Whether only thread moderators can act in the thread

boolean
total_message_sent#

Messages ever sent in the thread

number
type#

Thread type: 10 announcement, 11 public or 12 private

number

WireUser#

A public Fluxer account in the wire shape used by message authors, members and user reads

interface WireUser
avatar#

Avatar hash, or null when unset

string | null
avatar_color#

Generated avatar color, or null when unset

number | null
bot optional#

Whether the account is a bot, present on bot accounts

boolean
discriminator#

Four-digit discriminator string

string
flags#

Public account flag bits

number
global_name#

Display name, or null when unset

string | null
id#

Account snowflake ID

string
username#

Account username

string

Type Aliases#

TestBotOptions#

Options for createTestBot: The runBot options object of the bot under test, plus test settings

The signal, processSignals, reportFailure and drainMs settings are accepted and ignored, so the bot's own options object can be passed unchanged. An undefined token, such as an unset environment variable, uses the fixture token. Transport and instance belong to the test client

type TestBotOptions<
    F extends MessageFields | undefined = undefined,
    S extends Readonly<Record<string, unknown>>
        = Readonly<
            Record<string, CommandArgumentSchema | undefined>
        >
> =
    & Omit<BotOptions<F, S>, "token" | "transport" | "instance">
    & Omit<TestSettings, "token">
    & TestClockSettings
    & { readonly token?: string }type TestBotOptions<
  F extends
    | MessageFields | undefined
    = undefined,
  S extends Readonly<
    Record<string, unknown>
  >
    = Readonly<
      Record<
        string,
        | CommandArgumentSchema
        | undefined
      >
    >
> =
  & Omit<
      BotOptions<F, S>,
      | "token" | "transport"
      | "instance"
    >
  & Omit<TestSettings, "token">
  & TestClockSettings
  & { readonly token?: string }

TestClientOptions#

Options for createTestClient: Every createClient option except token, transport and instance, plus test settings

The token defaults to the fixture token, the transport is always the in-memory test transport and the instance is always hosted Fluxer served from memory

type TestClientOptions<
    F extends MessageFields | undefined = undefined
> =
    & Omit<ClientOptions<F>, "token" | "transport" | "instance">
    & TestSettings
    & TestClockSettingstype TestClientOptions<
  F extends
    | MessageFields | undefined
    = undefined
> =
  & Omit<
      ClientOptions<F>,
      | "token" | "transport"
      | "instance"
    >
  & TestSettings
  & TestClockSettings

TestRequestMatcher#

Select the requests a registered response answers

A string is "METHOD /path" or "/path" for any method, where a :name segment matches any single path segment, such as "POST /channels/:id/messages". A string starting with http matches an absolute URL on another origin. A RegExp is tested against the path. An object combines an optional method with a string or RegExp path, and a function decides from the whole request

type TestRequestMatcher =
    | string
    | RegExp
    | { readonly method?: string; readonly path: string | RegExp }
    | ((request: TestRequest) => boolean)type TestRequestMatcher =
    | string
    | RegExp
    | {
        readonly method?: string
        readonly path:
          | string | RegExp
      }
    | ((request: TestRequest)
        => boolean)

TestResponder#

Compute a response from the recorded request

A returned promise may settle later, and a handler that throws or rejects makes the request fail as a network error, which the client reports like any transport failure. That does not always fail the test, so check request contents with next() or requests() after the call instead

type TestResponder =
    (request: TestRequest) => TestResponse | Promise<TestResponse>type TestResponder =
    (request: TestRequest)
      =>
        | TestResponse
        | Promise<TestResponse>

TestResponse#

A response description

Omitted fields default to status 200 with a JSON body, or status 204 when body is omitted. A Response object is used unchanged for bodies that are not JSON

type TestResponse =
    | {
          readonly body?: unknown
          readonly headers?: Readonly<Record<string, string>>
          readonly status?: number
      }
    | Responsetype TestResponse =
    | {
        readonly body?: unknown
        readonly headers?: Readonly<
          Record<string, string>
        >
        readonly status?: number
      }
    | Response

WireOverrides#

Wire-field overrides for a fixture builder

Listed fields keep their wire types, and any other field is copied unchanged, so a test can add fields this SDK version does not model or pass undefined to leave a default field out of the payload

type WireOverrides<T> =
    & { readonly [K in keyof T]?: T[K] }
    & { readonly [key: string]: unknown }type WireOverrides<T> =
    & {
        readonly [K in keyof T]?:
          T[K]
      }
    & {
        readonly [key: string]: unknown
      }