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>
- Returns
TestBot<SelectedMessage<F>>
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, 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
optionsoptional-
TestClientOptions<F>
- Returns
TestClient<SelectedMessage<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: Fixturesimport { 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#
TestTimeout Error - A test wait, such as
TestRoute.next, idle or say, did not finish within thetimeoutMsthe test passed UnhandledTest Failures Error - 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 Fixturesids#-
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-
string
botUser #
Build the test bot account, the user that test clients report in READY
botUser(overrides?: WireOverrides<WireUser>): WireUserbotUser(
overrides?:
WireOverrides<WireUser>
): WireUserParameters
overridesoptional-
WireOverrides<WireUser>
- Returns
WireUser
channel#
channel(overrides?: WireOverrides<WireChannel>): WireChannelchannel(
overrides?:
WireOverrides<WireChannel>
): WireChannelParameters
overridesoptional-
WireOverrides<WireChannel>
- Returns
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>
): WireForumChannelParameters
overridesoptional-
WireOverrides<WireForumChannel>
- Returns
WireForumChannel
guild#
Build a community record, by default the default community owned by the default author
guild(overrides?: WireOverrides<WireGuild>): WireGuildguild(
overrides?:
WireOverrides<WireGuild>
): WireGuildParameters
overridesoptional-
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
): WireGuildCreateParameters
overridesoptional-
WireGuildCreateOverrides
- Returns
WireGuildCreate
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>
): WireMemberParameters
overridesoptional-
WireOverrides<WireMember>
- Returns
WireMember
message#
message(overrides?: WireOverrides<WireMessage>): WireMessagemessage(
overrides?:
WireOverrides<WireMessage>
): WireMessageParameters
overridesoptional-
WireOverrides<WireMessage>
- Returns
WireMessage
nextId #
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>
): WireRoleParameters
overridesoptional-
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>
): WireThreadParameters
overridesoptional-
WireOverrides<WireThread>
- Returns
WireThread
user#
Build a human account, by default the default author
user(overrides?: WireOverrides<WireUser>): WireUseruser(
overrides?:
WireOverrides<WireUser>
): WireUserParameters
overridesoptional-
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 optionsoptional-
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 Test: client, fixtures, rest, advance, commands, counters, disconnect, emit, emit, 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 AsyncDisposableclient#-
The client under test, created with
createClientUse it exactly as in the application
Client<M>
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#
commands(): readonly TestGatewayCommand[]- Returns
readonly TestGatewayCommand[]
counters#
The client's running totals, the same as client.diagnostics().counters
counters(): ClientCounters- Returns
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
): voidParameters
optionsoptional-
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 Event 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 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 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
): voidParameters
type-
string payload-
unknown optionsoptional-
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
): voidParameters
data-
GatewayErrorData optionsoptional-
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
optionsoptional-
TestWaitOptions
- Returns
Promise<void>
logs#
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 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
optionsoptional-
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 Unhandled 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 TestClockSettingsclockoptional#-
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.scheduledelays and intervals,waitForand collector timeouts, cooldowns in a command router's own store, cache expiry, member request timeouts, REST and presence pacing, thekeepTypingrefresh, reconnect delays and the gateway heartbeat. A cooldown store passed to a command, such ascommands, keeps its own time.memory Cooldowns() Date.now()and newDate()in application code, timers the application starts itself, thetimeoutMsof next, idle and say, and socket and process watchdogs keep real timeA client that owns more than one shard or uses automatic sharding throws
ConfigurationErrorwith "manual", because the SDK spaces several shards' Identify commands on the clock, and so does any other value"manual" | "real"
TestDisconnectOptions #
interface TestDisconnectOptionscodeoptional#-
WebSocket or gateway close code the client receives, default
4000(unknown error), after which the SDK reconnects and resumesEvery recoverable code resumes the same session, including 4007 (invalid sequence), so the shard's
sessionEpochstays the same. UseendSessionto start a new session. A fatal code such as 4004 ends the client's connection lifetime insteadnumber endoptional#Session -
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
sessionEpochincreases, 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 throwsConfigurationError. A fatal code still ends the client's connection lifetime, so combine this option with a recoverable codeboolean
TestEmitOptions #
interface TestEmitOptionsshardoptional#Id -
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 0number
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 TestGatewayCommandTestRequest #
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 TestRequestbody#-
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 TestRequestFileTestRest #
Register fake Fluxer HTTP API responses for a test client
Without a registration, message sends (POST /channels/:id/messages) and edits (PATCH /channels/:id/
interface TestRestrespond#
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
): TestRouteParameters
matcher-
TestRequestMatcher response-
TestResponse | TestResponder
- 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 TestRoutenext#
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
optionsoptional-
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(): voidrequests#
Requests this registration answered so far, in order
requests(): readonly TestRequest[]- Returns
readonly TestRequest[]
TestSayOptions #
Choose the message a test bot's say delivers and how long say waits for the bot to settle
interface TestSayOptions extends TestWaitOptionsinterface TestSayOptions
extends TestWaitOptionsmessageoptional#-
Wire fields that replace the defaults of the delivered MESSAGE_CREATE payload, as in
fixtures.messageBy default the message comes from the fixture set's human author in its default channel and community
WireOverrides<WireMessage>
Inherited from Test: timeout
TestSettings #
Settings that only test clients accept, alongside the usual client options
interface TestSettingsheartbeatoptional#Interval Ms -
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 tokenoptional#-
string useroptional#-
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 TestWaitOptionstimeoutoptional#Ms -
Milliseconds before the wait fails with
TestTimeoutError, an integer from 1 through 2,147,483,647Omit 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, throwsConfigurationErrornumber
WireChannel #
interface WireChannellast_#pin_ timestamp -
Latest pin time, or null when nothing is pinned
string | null name#-
Channel name
string 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
WireForumChannel #
interface WireForumChannelavailable_#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_#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 last_#pin_ timestamp -
Latest pin time, or null
string | null name#-
Channel name
string permission_#overwrites -
Role and member permission overwrites
readonly unknown[] position#-
Sorting position
number topic#-
Posting guidelines, or null when unset
string | null
WireGuild #
A community record in the wire shape of guild reads, GUILD_UPDATE and the properties of GUILD_CREATE
interface WireGuildafk_#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 mfa_#level -
MFA requirement level
number name#-
Community name
string nsfw#-
Whether the community is marked NSFW
boolean nsfw_#level -
NSFW classification level
number splash#-
Invite splash hash, or null when unset
string | null splash_#card_ alignment -
Splash card alignment, 0 for center
number 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 WireGuildCreatechannels#-
readonly (WireChannel | WireForumChannel)[]readonly ( | WireChannel | WireForumChannel)[] emojis#-
Community emojis
readonly unknown[] joined_#at -
ISO 8601 time the bot joined, or null
string | null presences#-
Always empty
Presences arrive as separate dispatches
readonly unknown[] stickers#-
Community stickers
readonly unknown[] threads#-
Active threads the bot can view, each with member when the bot joined it
readonly WireThread[]
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 WireMemberaccent_#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 joined_#at -
ISO 8601 join time
string nick#-
Community nickname, or null when unset
string | null
WireMessage #
A message in the wire shape of message reads, MESSAGE_CREATE and MESSAGE_UPDATE
interface WireMessageattachments#-
Attachments
readonly unknown[] channel_optional#type -
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 flags#-
Message flag bits
number memberoptional#-
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 itOmit<WireMember, "user" | "guild_id"> mention_#everyone -
Whether the message mentions everyone
boolean mention_optional#here -
Whether the message mentions here, which only MESSAGE_CREATE carries and Fluxer sends only as true
boolean nicksoptional#-
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 #
interface WireRoleWireThread #
A thread in the wire shape of thread reads, thread lists and THREAD_CREATE and THREAD_UPDATE
interface WireThreadflags#-
Channel flag bits, where 2 pins a forum post
number last_#pin_ timestamp -
Latest pin time, or null when nothing was pinned
string | null memberoptional#-
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
message_#count -
Messages in the thread
number name#-
Thread name
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 invitableoptional-
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 WireUseravatar#-
Avatar hash, or null when unset
string | null avatar_#color -
Generated avatar color, or null when unset
number | null botoptional#-
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 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
& TestClockSettingsTestRequestMatcher #
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/
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
}
| ResponseWireGuildCreateOverrides #
Overrides for a GUILD_CREATE fixture
The guild field merges into the default community record, and the other fields replace the default body fields
type WireGuildCreateOverrides =
& WireOverrides<Omit<WireGuildCreate, "properties">>
& { readonly guild?: WireOverrides<WireGuild> }type WireGuildCreateOverrides =
& WireOverrides<
Omit<
WireGuildCreate,
"properties"
>
>
& {
readonly guild?:
WireOverrides<WireGuild>
}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
}