Mocks
Stand in for discord.js interactions, messages, users and Discord's errors, with the rules discord.js follows.
You'll learn
- Mock any discord.js class, with the properties a test needs
- Build a command's options, a modal's fields, a message, and a member with roles and permissions
- Run discord.js's collectors on mocks, and have a mock's values type-checked
- Reset mocks between tests, and reject with Discord's own errors
Before this
A handler takes discord.js objects: an interaction, a message, a reaction, the user behind them. meocord/testing
mocks every one of them. A mock keeps its class's prototype chain, so instanceof holds at every level and a mock can
go straight to code that expects the real class.
Every method is a mock function, with .mock.calls, which Vitest's and Jest's matchers read. Vitest's toHaveResolved
and toHaveBeenCalledBefore read MeoCord's own mocks too. Their call order is counted across MeoCord's mocks, so
compare two of MeoCord's mocks, or two of the runner's, rather than one of each. Once
useMockFn is called, each of these methods is your test runner's own mock, and the runner
treats it as one of its own.
Under Node's test runner, assert through .mock.calls itself: each call is recorded as an array of its arguments,
mock.calls[0][0], not node:test's { arguments } record.
When to use it
Use these mocks for the inputs a testing module runs, and for services that read discord.js objects. They follow discord.js's rules, so a handler that replies twice, or reads a server outside one, fails in the test as it would in the bot.
For a value you own, such as a service's settings, pass a plain object or use
overrideProvider instead. A mock is for what Discord sends.
Example
it('behave like the real class', async () => {
const interaction = createMockInteraction(ChatInputCommandInteraction)
// instanceof holds at every level, and type guards run discord.js's own logic
expect(interaction).toBeInstanceOf(BaseInteraction)
expect(interaction.isChatInputCommand()).toBe(true)
expect(interaction.isButton()).toBe(false)
// Replying twice throws, as it does against Discord
await interaction.reply({ content: 'hi' })
expect(interaction.replied).toBe(true)
await expect(interaction.reply({ content: 'again' })).rejects.toThrow()
// Every method is still a mock function
expect(interaction.reply).toHaveBeenCalledWith({ content: 'hi' })
})createMockInteraction(Class, overrides?) mocks the class you pass, here a
slash command. Its type guards and its replies behave as discord.js's do, and each call is recorded.
How it works
A mock is built from the class's prototype, with its methods replaced by mock functions:
- Type guards run discord.js's logic.
isButton(),isRepliable(),isChatInputCommand()and the rest answer from the class the mock was made from, all but the deprecatedisSelectMenu(), which returnsundefined: useisStringSelectMenu(). They're still mock functions, so a test can override one. - Replies follow Discord's rules. Replying or deferring twice throws discord.js's
InteractionAlreadyRepliederror, andfollowUp(),editReply()anddeleteReply()throwInteractionNotRepliedbefore any reply. An answer a test gives a value withmockResolvedValueormockImplementationcounts as one. Under strict mocks, an interaction is markedreplied,deferredorrespondedonce its answer resolves, as discord.js marks it, so aneditReply(),followUp()ordeleteReply()made before an un-awaited first answer resolves rejects withInteractionNotReplied, and a second answer sent while the first is in flight is refused with Discord's 40060. A mock answer lands one microtask after the call, so strict mocks catch an edit or a second answer only when the code makes it before awaiting anything; after anyawaitin between, the first answer has landed. In default mode the flags are set at the call, and the first overlap a bot would refuse warns.fetchReply()reads back whatreply()orupdate()sent, as it was sent: a builder changed afterwards doesn't change it. AfterdeleteReply(), and after a command shows a modal,editReply(),fetchReply()anddeleteReply()reject with Unknown Message (10008), as doesfetchReply()before any answer. A follow-up is reached by its id:editReply({ message: followUp.id }), andfollowUp()resolves to the follow-up it sent, asfetchReply(id)reads it. Under strict mocks, an answer whose components or embeds discord.js refuses to build, such as a button with no label, rejects at the call and leaves the interaction as it was; in default mode it warns once and is built when first read.flagsare read as discord.js reads them, a number, an array, a name or a bitfield. An autocomplete'srespond()works once, and refuses more than 25 choices. - Ids are Discord's shape. An interaction gets an
id, achannelIdand auser, a person rather than a bot, each a snowflake no other mock in the run has. So does a user or an attachment made withcreateMockInteraction, and a message context menu'stargetIdis itstargetMessage's, or one made for its own id. Every generated id, a server'sownerIdand a command'scommandIdincluded, comes from one count, so a run gives the same ids each time, and a value made on its first read is kept. Two mocks are two users, so a per-user cooldown counts them apart; give them oneuser, or one messageauthor, to count them together. Ids you give are kept. - Creation times come from the id, as discord.js reads them:
createdTimestampandcreatedAtare the time anidyou give encodes, a thread's included. With a generated id, a message and an interaction were created when the mock was made. Under strict mocks so were a user, server and channel; in default mode they read their generated id's time, a day in 2025, with a warning. AcreatedTimestampyou set wins. - A mock without a
guildIdis a DM.inGuild(),inCachedGuild()andinRawGuild()answer from the mock'sguildIdandguild, and in a DMguildandmemberarenull. UnderuseStrictMocks(), a givenguild, or amember's guild, fills the interaction'sguildId. In default mode, give the interaction itsguildIdwith itsguildormember: aguildalone leaves it a DM that still has thatguild, and amemberalone a DM with thatmemberand noguild, and the mock warns. - An interaction has the channel it came from. In a server,
channelis a text channel of that server, the one itsguildcaches underchannelId; in a DM, it's the user's DM channel. Itssend()resolves, and its type guards, such asisTextBased(), answer as discord.js's do. - A channel you give sets where the mock is. Given to
createMockInteractionorcreateMockMessage, it sets thechannelId,guildIdandguildyou leave out: a DM channel makes the mock a DM, and a server's channel puts it in that server. A server's channel that names no server goes in the mock's. A channel in another server than theguildyou give, or a DM channel beside aguildId, is refused, naming both. - Under strict mocks, a message, guild or guildId places it too. An interaction given a
messageis in the message's channel and server; given aguild, or a member of a server, it is in that server; given aguildIdalone, it is in a server the bot isn't in, withguildandchannelnulland a raw member. Achannel,guildorguildIdother than a place the test gave the message is refused, naming both; a message whose placecreateMockMessage()made itself moves to the interaction's. In default mode only a channel places it, and reading where it is warns once where strict mocks place it otherwise. - A member has roles and permissions. An interaction's or a message's
memberhas the server's @everyone role, andpermissionsandmemberPermissionsare computed from its roles as discord.js computes them, so a role or permission guard runs on a mock as it does in Discord. UnderuseStrictMocks(),memberPermissionsapplies the interaction's channel's overwrites on top of them, a thread's parent's for a thread, as discord.js does, and an administrator or the server's owner has every permission. In default mode it leaves them out, and warns where they would differ. - A select menu has picked nothing unless given. Its
valuesare an empty array, and so are the collections of what its kind picks:usersandmembers,roles, orchannels, each an emptyCollection. Give the choices a test needs in the overrides, as theCollections discord.js holds: itsvaluesare then their ids, as Discord sends them. - An interaction has a client. One made without a
clientgets one fromcreateMockClient(), as a message does: its user is inclient.users.cache, its channel inclient.channels.cacheonce read, andclient.useris the mock bot. Under strict mocks it shares that client with what it holds, as in discord.js: its user, member, channel and server, a message's author and the users it mentions, and what its options or a select menu resolve to. It takes theclientgiven, else the mock client amessage,channelorguildgiven already holds, else a new one, socreateMockMessage({ channel })is on the channel's client. In default mode each keeps a client of its own, and code that reads one where strict mocks give another warns once. - Locales are set as Discord sends them.
localeis'en-US', andguildLocaleis'en-US'in a server andnullin a DM, so a translator works on a default mock.
it('reads an interaction’s creation time from its id, as discord.js does', () => {
const before = Date.now()
const made = createMockInteraction(ButtonInteraction, { customId: 'x' })
const given = createMockInteraction(ButtonInteraction, { customId: 'x', id: '1200000000000000000' })
// A generated id: the time the mock was made
expect(made.createdTimestamp).toBeGreaterThanOrEqual(before)
// An id you give: the time it encodes
expect(given.createdAt).toEqual(new Date(SnowflakeUtil.timestampFrom('1200000000000000000')))
})Overrides
The second argument sets properties as the mock is built. It's the only way to set what discord.js makes read-only, such
as a modal's customId and fields, or the client. A misspelled property name is a compile error.
To put a command somewhere a user-installed app can be used, set context and authorizingIntegrationOwners:
const at = (context: InteractionContextType, owners?: Partial<Record<ApplicationIntegrationType, string>>) =>
getInstallContext(
createMockInteraction(ChatInputCommandInteraction, { context, authorizingIntegrationOwners: owners }),
)
describe('getInstallContext', () => {
it('tells the four places a command can run apart', () => {
// The bot's own server, installed to the server
expect(
at(InteractionContextType.Guild, { [ApplicationIntegrationType.GuildInstall]: '876543210987654321' }),
).toEqual({
where: 'guild',
botInstalled: true,
})
// A server without the bot, through a user install
expect(
at(InteractionContextType.Guild, { [ApplicationIntegrationType.UserInstall]: '123456789012345678' }),
).toEqual({
where: 'guild',
botInstalled: false,
})
expect(at(InteractionContextType.BotDM)).toEqual({ where: 'bot-dm', botInstalled: true })
expect(at(InteractionContextType.PrivateChannel)).toEqual({ where: 'private-channel', botInstalled: false })
})
})Under strict mocks, a guild places it in that server, and a guildId alone in a server the bot isn't in, with a raw
member. In default mode, give a server's guildId with its guild, and for a server the bot isn't in a member from
createMockRawMember(), as A server the bot isn't in shows.
Options and fields
createChatInputOptions(record) builds a command's or an autocomplete's options,
found by name as the real resolver finds them:
it('take options as Discord sends them', () => {
const interaction = createMockInteraction(ChatInputCommandInteraction)
interaction.options = createChatInputOptions({
subcommandGroup: 'admin',
subcommand: 'ban',
reason: 'spam',
days: 7,
})
expect(interaction.options.getSubcommand(true)).toBe('ban')
expect(interaction.options.getString('reason')).toBe('spam')
// An option of another type, or a required one that is absent, throws discord.js's error
expect(() => interaction.options.getString('days')).toThrow('Option "days" is of type: 4; expected 3.')
expect(() => interaction.options.getNumber('missing', true)).toThrow('Required option "missing" not found.')
// data is nested under the subcommand path, as MeoCord reads it to build a handler's params
expect(interaction.options.data[0]).toMatchObject({
name: 'admin',
type: ApplicationCommandOptionType.SubcommandGroup,
})
})- A user, role, channel or attachment option is set both as the id and as the resolved object, so a handler that reads
only one of the two is caught.
getAttachment()returns theAttachmentgiven, andnullfor an option not given. A user option carries its user, and in a server its member:getMember()isnullin a DM, and a member you give answersgetUser()with its user. In an autocomplete, Discord sends a user, member, role, channel, mentionable or attachment option as its id: under strict mocks it holds the id only, as the handler's params do, and its getter returnsnull, or throws discord.js's error when asked withrequired: true. Give the object, not a bare id, which reads as a string option. In default mode the object is kept, and a warning names the options once. - Each getter reads its option as discord.js does, and throws discord.js's own error: a
TypeErrorwith itscode. A getter of another type throws, whether or not it's asked withrequired: true:getInteger()on1.5, a number option, throwsOption "x" is of type: 10; expected 4., while a whole number reads as either. A user or member read as a role, or a role read as a user or member, isnull, or that error when asked withrequired: true, since the option may be a mentionable one. - A missing option asked with
required: truethrowsRequired option "x" not found., andgetSubcommand()throws when there's none, unless givenfalse, as in discord.js. So doesgetChannel()givenchannelTypes, for a channel of another type, andgetFocused()when no option isfocused. subcommandGroup,subcommandandfocusedare reserved names: the last names the option an autocomplete is typing. Its value reads as Discord sends it, a string,''when none is given, throughgetFocused(),getFocused(true)andoptions.dataalike. A number given for it is its digits under strict mocks. The focused option is inoptions.data, so with no value given an autocomplete handler's params hold it as'', such as{ query: '' }.- Under strict mocks the focused option is read by its name too, as discord.js reads it: before anything is typed
getString()reads''andget()returns it, markedfocused; a typed whole number reads throughgetInteger()only, and one with a fraction throughgetNumber(), andgetString()on either throws discord.js's type error; and one given no value takes any of the string, integer and number getters, since the mock doesn't know its declared type. In default mode these getters read as before,nullfor an option given no value, with a warning once. getMentionable()on a user option returns the user's member in a server and the user in a DM under strict mocks, as discord.js readsmember ?? user. In default mode it returns the user, with a warning once.
A modal's submitted fields come from createModalFields({ body: 'It crashed' }), which
discord.js doesn't let a test build. A file upload field takes an array of Attachments:
createModalFields({ screenshot: [attachment] }). An empty array is a select with nothing chosen. Give an upload at
least one Attachment.
Messages, servers and the rest
createMockMessage()mocks a message that tracks whether it was deleted:delete(),edit(),reply(),react(),pin()andunpin()throw once it is. It takes anid,content,components,embedsandflags, and builders or JSON forcomponentsandembeds. It holds them as discord.js's classes, anActionRowwith itsButtonComponents, aContainerComponent, anEmbedand the rest, built from their JSON at the time of the call. What the content mentions is cached as the gateway delivers it: a<@id>in the client'susers.cache, and in a server inguild.members.cache; a<@&id>role and a<#id>channel in their caches too.authorsends a message as a user you give, such as one fromcreateMockUser(), orclient.userfor one the bot sent. It's cached on the client, and in a server the message'smemberis the guild's cached member for that user, made and cached when there's none. Every message from that author in oneguildyou give has the same member, and so does an interaction given the sameuserandguild, with itsguildIdin default mode.message.memberreads that cache each time, so a test that deletes the author's member fromguild.members.cachegetsnull, as discord.js gives for an author it hasn't cached.createMockGuild({ members, roles, channels })puts those in the server's caches, where a command's typed params are read from. Give it tocreateMockMessage({ guild }), or passguild: nullfor a DM.createMockClient()has real, emptyusers,channelsandguildscaches, and a bot user asclient.user, with the same id in every mock client, so a message can mention the bot by it.createMockMember({ user, guild, roles, nickname })makes a member with the roles given; see Members and roles.createMockUser()mocks a person,bot: false. A DM to the user, or to a member of theirs, goes through the user's one DM channel, whichcreateDM()resolves to. That channel has the user as itsrecipient, and is the user'sdmChannelonce made. Under strict mocks, a client'susers.createDM(user)resolves to it andusers.send(user, options)sends through it, and the channel'sclientis the user's. In default modeusers.createDM()gives every user the same channel,users.send()resolves to an empty message, and a test that reads a DM channel'sclientgets a client of its own, each with a warning once.createMockChannel(Class)mocks a channel of the class you pass, such asTextChannelorThreadChannel. Its type guards answer for that class, and its managers,messages,threadsormembers, have real, empty caches, with the channel as theirchannel, and asthreadon a thread'smembers. Give one tocreateMockMessage({ channel })to send a message there, or to an interaction to have it come from there.createMock<Interface>()mocks a type with no class at runtime, such as a service's interface. A type has no shape at runtime, so every property is a mock function, data included:if (settings.enabled)always passes. Pass the values the code reads,createMock<Settings>({ enabled: false }).
Two messages from one author count against that user's cooldown, as they would from one person in Discord:
it('counts two messages from one author against that member’s cooldown', async () => {
const module = MeoCordTestingModule.fromApp(App).compile()
const ana = createMockUser()
const first = createMockMessage({ author: ana, content: '!daily' })
const retry = createMockMessage({ author: ana, content: '!daily' })
await module.dispatch(first)
await module.dispatch(retry)
expect(first.reply).toHaveBeenCalledWith('You claimed 100 coins. Come back tomorrow.')
// The same author, so the same user's cooldown refuses the second
expect(retry.reply).not.toHaveBeenCalled()
})A message and an interaction from that user in one server share the member:
it('gives a message and an interaction from one user in one server the same member', () => {
const ana = createMockUser()
const guild = createMockGuild()
const message = createMockMessage({ author: ana, guild })
const click = createMockInteraction(ButtonInteraction, { user: ana, guild, guildId: guild.id })
expect(click.member).toBe(message.member)
expect(guild.members.cache.get(ana.id)).toBe(message.member)
})Members and roles
createMockMember({ user, guild, roles, nickname }) makes a member of a server, with
the roles you give. Put it in createMockGuild({ members }), and an interaction or a message from its user in that
server has it as its member, so a role guard sees its roles:
it('lets in a member with a required role, and no one without it', async () => {
const moderator = createMockInteraction(Role, { id: ROLE_IDS.moderator, name: 'moderator' })
const ana = createMockUser()
const guild = createMockGuild({ members: [createMockMember({ user: ana, roles: [moderator] })] })
const fromAna = createMockInteraction(ChatInputCommandInteraction, { user: ana, guildId: guild.id, guild })
const fromStranger = createMockInteraction(ChatInputCommandInteraction, { guildId: guild.id, guild })
await expect(module.invoke(ModerationSlashController, 'ban', fromAna)).resolves.toEqual({ ran: true })
await expect(module.invoke(ModerationSlashController, 'ban', fromStranger)).resolves.toEqual({ ran: false })
})A role is a mock Role with the id a guard checks: createMockInteraction(Role, { id }). The member's
roles.cache holds the server's @everyone role, then the roles given, and roles.add(), remove() and set() change
them. roles.highest ranks them by position, then by id. Its permissions combine its roles', @everyone's included,
and the server's owner has every permission:
it("takes a member's permissions from its roles, @everyone's included", () => {
const kick = createMockInteraction(Role, {
permissions: new PermissionsBitField([PermissionFlagsBits.KickMembers]),
})
const member = createMockMember({ roles: [kick] })
expect(member.permissions.has(PermissionFlagsBits.KickMembers)).toBe(true)
expect(member.permissions.has(PermissionFlagsBits.BanMembers)).toBe(false)
expect([...member.roles.cache.values()]).toEqual([member.guild.roles.everyone, kick])
})What discord.js computes from these, the mocks compute too, and keep computing after resetAllMocks():
role.comparePositionTo(other)andguild.roles.comparePositions(a, b)rank by position, then by id;channel.permissionsFor(member)andmember.permissionsIn(channel)apply the channel'spermissionOverwritesto the member's roles, and an interaction'sappPermissionsare the bot's in its channel. A thread'spermissionsFor()reads its parent's under strict mocks, and returnsundefinedin default mode;- a manager's
resolve()andresolveId()read its cache, given an id or the item, andguild.members.resolve(user)finds that user's member; guild.members.meis the bot's member: the cached one forclient.user, or one with @everyone, made once.
A member made without a server joins the one whose members it's given to. An interaction's channel is one of that
server's, and a manager's fetch(id) finds what the server caches:
it('answers in the channel the interaction came from, and finds a member by id', async () => {
const ana = createMockMember()
const guild = createMockGuild({ members: [ana] })
const interaction = createMockInteraction(ChatInputCommandInteraction, { guildId: guild.id, guild })
const channel = interaction.channel as TextChannel
await channel.send('Posted here.')
expect(channel.send).toHaveBeenCalledWith('Posted here.')
expect(guild.channels.cache.get(interaction.channelId)).toBe(channel)
await expect(guild.members.fetch(ana.id)).resolves.toBe(ana)
})A server the bot isn't in
A user-installed command can run in a server the bot isn't in. discord.js then has no server to cache the member in,
so interaction.member is the member Discord sent: plain data, with roles as role ids and permissions as a
string. createMockRawMember() builds it. Give it as the interaction's member,
with the server's guildId and no guild or channel:
inRawGuild()is true andinCachedGuild()false, andguildandchannelarenull, with itschannelIdkept;useris the member's user, andmemberPermissionsare thepermissionsyou give the raw member, which Discord sends with the channel's overwrites applied;- a user option's member is the member Discord resolves, with
rolesandpermissionsbut nouser; - the interaction is typed as discord.js types one from such a server, so the compiler sees
memberas raw data.
It takes the roles, permissions and user to give it, such as
createMockRawMember({ roles: [moderatorId], permissions: [PermissionFlagsBits.KickMembers] }). A guard that reads
member.roles.cache throws there, as it does in Discord, so a test of such a command finds the branch a handler needs:
interaction.inCachedGuild() before reading the cache, or member.roles as ids.
What methods return
A method that returns a promise in discord.js resolves, so await and .catch() work with no setup. A server's
emojis, stickers, scheduledEvents, autoModerationRules and invites managers answer as its other managers do:
| Method | Resolves to |
|---|---|
send(), a message's reply(), crosspost(), forward(), and an interaction's editReply(), followUp(), fetchReply() | a mock message in the channel it was sent in, holding what was sent |
an interaction's reply(), deferReply(), update(), deferUpdate() | undefined; under strict mocks, a mock InteractionResponse |
an interaction's showModal() | undefined |
a manager's fetch(id), or fetch({ user }) and the like | its cached item with that id, a message made in that channel, or a new one it caches |
a guild's members.fetch({ user: ids }) | a Collection of each, as fetch(id) gives it |
a manager's fetch() for a list | an empty Collection; under strict mocks, a channel's messages |
a manager's create() and edit() | a mock of its item; under strict mocks, the item asked for |
createDM() | the user's DM channel |
a member's kick(), ban() and timeout() | the member |
awaitMessages() and awaitReactions() | an empty Collection; under strict mocks, what they collect |
a structure's own edit(), fetch(), delete() and setters, but a message's delete() | the structure itself |
a message's delete(), pin() and unpin() | undefined |
| any other method that returns a promise | undefined |
it('resolves methods that return a promise in discord.js to something to work with', async () => {
const client = createMockClient()
const guild = createMockGuild()
const channel = createMockChannel(TextChannel)
// send() and reply() resolve to a message, so .catch() and awaited results just work
await expect(client.users.send('1', 'hi').catch(() => undefined)).resolves.toBeInstanceOf(Message)
// A manager's fetch by id resolves to that item, and a list fetch to an empty collection
await expect(client.users.fetch('1')).resolves.toBeInstanceOf(User)
await expect(guild.members.fetch('1')).resolves.toBeInstanceOf(GuildMember)
await expect(guild.members.fetch()).resolves.toEqual(new Collection())
// A structure's own edits and setters resolve to the structure
await expect(channel.setName('general')).resolves.toBe(channel)
})Under strict mocks, an interaction's four answers resolve to what discord.js's do. The mock InteractionResponse is
bound to the interaction: its edit(), delete() and fetch() reach editReply(), deleteReply() and
fetchReply(), and its createMessageComponentCollector() runs a collector on the reply, as
Collectors shows. With withResponse: true, each resolves to an InteractionCallbackResponse:
reply()'s anddeferReply()'sresourceis of typeChannelMessageWithSourceand holds the message asfetchReply()reads it then, fordeferReply()the loading message, whose id the reply keeps;update()'s is of typeUpdateMessageand holds the updated message;deferUpdate()has noresource: it isnull.
A deferred reply reads as Discord shows it until it is edited: fetchReply() after deferReply() gives a message
flagged Loading, and Ephemeral too for a private deferral. An edit clears Loading. respond(interaction).send()
resolves to the message the reply or the update sent. In default mode the four resolve to undefined, and the first
time a test's or an app's own code calls one, a warning is logged for the run.
fetchReply(), editReply() and followUp() each resolve to a new message object, the message as it stands then, as
discord.js returns a copy rather than its cached Message. Two fetchReply() calls aren't ===, and a message held
from before an edit keeps its old content: compare messages by id, and tell two edits apart by editedTimestamp.
Under strict mocks, a channel caches each message made in it, or sent there through send() or reply(), as
discord.js caches messages as they arrive, and its messages.fetch() with no id lists them, newest first, honouring
limit, 50 by default, before, after and around. guild.channels.create() makes the type its options name, a
manager's edit(id, options) resolves to the item with that id, and a name given to create() or edit() names
the item. In default mode a channel's messages.cache stays as it was, fetch() for a list resolves to an empty
Collection, create() makes a text channel, and edit() a new item under another id, each with a warning once. In
both modes a thread a channel's thread manager creates or fetches has that channel as its parent.
A method that returns a value at once returns what discord.js computes where the mock has what it needs: resolve(),
comparePositionTo(), permissionsFor() (a thread's, or a channel's made without a server, only under strict
mocks), message.mentions.has(user),
isReady(), and avatarURL() and iconURL(), null with no avatar or icon set. Any other returns undefined. A test
still decides with mockReturnValue, mockResolvedValue and mockRejectedValue.
Values discord.js computes
Some of what discord.js computes depends on Discord's state: who sent a message, the bot's roles and permissions, a channel's overwrites. Unless told otherwise, a mock reads these as a truthy placeholder:
- a message's
editable,deletable,pinnable,crosspostable,bulkDeletableandhasThread; - a member's
manageable,kickable,bannableandmoderatable; - a role's
editable, and a channel'sviewable,manageableanddeletable, and their thread and voice counterparts, a voice channel'sfullamong them; partialon messages, users, channels and reactions.
The first time a test reads one, the run logs a warning that names it and says how to set it. Set the value the test
relies on, such as message.editable = false or member.kickable = false, and it is read without a warning.
Some data discord.js gives empty, null or false, also reads as a truthy placeholder: a reaction's me,
message.mentions.repliedUser, a message's editedAt, a member's presence, a server's verified and
systemChannel, a channel's parent, and a modal's message. A reaction made without a message has a placeholder
message too, though discord.js always gives a reaction its message. Reading one warns the same way, naming the value
to set, such as reaction.me = false or reaction.message = createMockMessage(). When MeoCord's dispatcher reads a
reaction's placeholder partial, it fetches the reaction, and the warning says so: set reaction.partial = false and
reaction.message.partial = false, or use strict mocks.
message.thread is the thread the message's channel caches under the message's id. For a message that started a thread,
cache one on the message's channel with channel.threads.cache.set(message.id, thread as PublicThreadChannel<false>),
thread from createMockChannel(ThreadChannel). Without one, it is a placeholder thread, with a warning, since
discord.js reads null there.
A property the mock's discord.js class doesn't have, such as isRepliable on a message, or guild on a class
without one, reads a placeholder too. The first read of one by a test's or an app's code warns once for the run, naming
it, its class and what strict mocks answer; MeoCord's own reads stay quiet.
Strict mocks
useStrictMocks(), called once in a test setup file before any mock is made, has the
mocks compute each of these with discord.js's own code, and message.thread read null without a cached thread. No
placeholder warning is logged. The mocks hold what those computations read, as Discord sends it:
- the bot's member is in its server's member cache from the start;
- @everyone has the permissions Discord gives it in a new server: the bot can view and send in a channel and join a
voice channel, but not manage, pin, kick or ban. In default mode it has none, and a read that would differ warns until
the test gives @everyone its permissions, as a role with the server's id, which is its @everyone:
createMockGuild({ id, roles: [createMockInteraction(Role, { id, permissions })] }); - a channel or thread made without a server has one of its own, a thread with a text channel as its parent. In
default mode such a channel's
permissionsFor(),overwritesFor(),memberPermissions()androlePermissions()returnundefined, as a thread's do, with a warning once; - a client's
users.createDM()andusers.send()reach the user's own DM channel, whoseclientis the user's; - a channel caches the messages made or sent in it, and its
messages.fetch()with no id lists them; guild.channels.create()makes the type named,create()andedit()apply aname, andedit(id)resolves to that item;- those values read as discord.js gives them:
meisfalse,repliedUserand a modal'smessagearenull, andeditedAt,presence,verified,systemChannelandparentare computed from what the mock holds; - a reaction made without a message has a whole one, so a dispatched reaction isn't fetched;
- a message the bot sends is its
client.user's, and one it sends in a DM is in that DM; - an autocomplete's user, member, role, channel, mentionable or attachment option is its id, as Discord sends it,
and its focused option is read by name,
''before anything is typed; getMentionable()on a user option gives the user's member in a server;- an interaction's
ephemeralisnulluntilreply()ordeferReply()decides it. In default mode it readsfalseuntil then, and reading it warns once. Afterupdate()ordeferUpdate(), or once the test setsdeferreditself, it readsnullin both modes, as discord.js does; - an edit changes only the flags Discord lets it change:
SuppressEmbeds, andIsComponentsV2, which it sets and never clears. That holds foreditReply(),update()and a mock message'sedit(), so a private deferral edited into a Components V2 message stays private, andflags: 0leaves a V2 message V2. In default mode an edit's flags replace the message's, with a warning once where strict mocks would keep one,respond()'s own edits included; - a Components V2 message can't hold
contentorembeds. A reply, follow-up, edit or update that leaves one holding them is refused withcreateDiscordError(50035)and changes nothing: one sent so, or one made V2 by an edit that doesn't clear them withcontent: nullandembeds: []. So are a channel's, user's or member'ssend()and a message'sreply(). Default mode sends it, with a warning once. An edit'scontent: nullreads back as'', as discord.js sends it; - a message holds the files sent with it as uploads, as Discord does: an embed's image and a Components V2
component's media show their upload by CDN URL, the component's with
attachment_id, andattachmentslists only the uploads nothing shows. An edit withfilesorattachmentskeeps only the uploads it lists, none when it lists noattachments, as discord.js then sends the new files alone, and media whose upload it removed reads back not found, withloading_state3. A component'sattachment://reaches a kept upload only in an edit with noattachments, or one that lists it as{ id, filename }. Discord's 400 refuses any other, an id the message doesn't have, an upload listed under another filename, and a File pointed at a URL. An embed'sattachment://reaches a kept upload however it is listed. A name reaches a new file of that name first, then the newer of two kept uploads sharing it, and a CDN URL from another channel is an image the message doesn't hold. Default mode holds files nowhere, with a warning once; - a property the class doesn't have reads
undefinedand isn'tinthe mock, as on discord.js's objects, somessage.isRepliable?.()isundefinedandif (value.guild)is false for a class without aguild.inis true for a field the class sets on its instances, such as'content' in message, read from the discord.js the app installed. A property the test gives or assigns, and a mock of an app's own subclass, answer as before; - an interaction's
reply(),deferReply(),update()anddeferUpdate()resolve to a mockInteractionResponse, or withwithResponseanInteractionCallbackResponse, as What methods return describes; - a mock and what it holds are on one client, as How it works describes;
- the mock client's emitter works, and collectors run discord.js's own code, as Collectors shows. A
command's
message, and a message's rawchannel_idandguild_id, readundefined, as on discord.js's classes.
So a message another user sent isn't editable or deletable, and a member isn't kickable until the bot's member has
a role above theirs with Kick Members. Give the bot's member that role, through guild.members.me!.roles.add(role), and
the values follow. A value the test sets on a mock still wins over the computed one. Under strict mocks, invoke also
refuses a handler given fewer arguments than it declares where it builds none, such as a reaction handler given the
reaction without its ReactionEvent, naming what to pass, and an autocomplete that dispatch gives to another
@Autocomplete handler or to none; compile() refuses an override stub without its stage's method. A generated
project's vitest.setup.ts makes this call. A second answer after one a test set, which discord.js refuses, runs with a
warning in default mode; under strict mocks it throws, as discord.js does.
A testing module follows the bot more closely under strict mocks too, each with a warning once in default mode:
dispatch()reports a call whose answer fails to build once, as'error', as the bot does. In default mode an interaction's observers hear it twice, first with its own outcome.dispatch()rejects with that failure either way.dispatch()leaves a component no route takes to the mock client'sinteractionCreatelisteners, and delivers a message or a reaction to itsmessageCreateand reaction listeners, as Invoke and dispatch describes.emit()sets the module's presenter, theme and translator on the client of each event argument, as the bot sets them on its own client, and a module without a presenter answers with MeoCord's default on a client another module used.init({ ready: true })andclose()run the lifecycle hooks of a class that only a guard, an interceptor, a pipe, a filter or the presenter injects in the bot's order: itsonReadyafter the controllers' and observers', and itsonShutdownbefore theirs. Default mode warns once, naming the first class whose hooks run in another order.inspectHandlerlists only the guards, interceptors and observers dispatch runs for the handler's context types, and itsinheritedRoutesnames an inherited@Onor@Onceevent too, such asevent "guildCreate", which default mode leaves out.
Collectors
Under strict mocks, a collector runs discord.js's own code on the mock client, so a handler that collects runs in its test as it does in the bot:
createMessageComponentCollector()andawaitMessageComponent(), on a message, on anInteractionResponseor on a text channel, collect a click thatmodule.dispatch()delivers or that a test emits on the client;- a channel's
createMessageCollector()andawaitMessages(), and a message'screateReactionCollector()andawaitReactions(), collect the messages and reactionsdispatch()delivers; max,filter,componentType,time,idle,disposeandstop()work as in discord.js, and the await methods resolve with what they collected, or reject on theirtime. Each method stays a mock function that records its calls.
A click built from the reply, with message: await interaction.fetchReply(), is on the reply's client, so dispatch()
delivers it where the collector listens:
it('run on the reply, and hear a click built from it', async () => {
const module = MeoCordTestingModule.fromApp(PollApp).compile()
const command = createMockInteraction(ChatInputCommandInteraction, { commandName: 'poll' })
await module.dispatch(command)
// Built from the reply, the click is on the client the collector listens on
const vote = createMockInteraction(ButtonInteraction, {
customId: 'poll-pizza',
message: await command.fetchReply(),
})
await module.dispatch(vote)
expect(getResponse(vote)).toMatchObject({
sent: true,
calls: [{ method: 'update', payload: { content: 'Counted: poll-pizza' } }],
})
})To answer awaitMessageComponent() or awaitMessages(), start the handler without awaiting it, dispatch the answer
once the handler has asked, then await the handler:
it('collect the answer a handler waits for', async () => {
const module = MeoCordTestingModule.fromApp(PollApp).compile()
const ask = createMockMessage({ content: '!quiz' })
// Started, not awaited: the handler waits for the answer
const asked = module.dispatch(ask)
await vi.waitFor(() => expect(ask.reply).toHaveBeenCalledWith('What is 2 + 2?'))
await module.dispatch(createMockMessage({ content: '4', author: ask.author, channel: ask.channel }))
await asked
expect(ask.reply).toHaveBeenLastCalledWith('Correct!')
})discord.js times a collector's time and idle with node:timers, so a test's fake timers don't move them. A handler
that awaits awaitMessages({ time: 60_000 }) with nothing dispatched waits that long, past a test's timeout: dispatch
the answer, give the collector max, or call collector.stop().
In default mode the create methods return undefined, the await methods resolve at once to an empty Collection, and
the first call an app's or a test's code makes to one warns once. A mock on a real discord.js Client keeps them
inert in either mode.
A collector's callback answers a click with respond() after the handler has returned. It takes the theme of the app
the click's client belongs to, so a click a test builds must come from the same client as the call that started the
collector. The gateway does that for the bot; in a test, build the click from the reply as above, or pass
{ client: interaction.client }:
it('takes the module’s theme when the click comes from the client the call came to', async () => {
const module = MeoCordTestingModule.create({ app: PollApp, controllers: [PollController] }).compile()
const open = createMockInteraction(ButtonInteraction, { customId: 'poll/open' })
await module.dispatch(open)
// The gateway gives a collector's click the bot's client
const vote = createMockInteraction(ButtonInteraction, { customId: 'poll-vote', client: open.client })
await onCollect!(vote)
const { embeds } = getResponse(vote).calls[0].payload as { embeds: { color?: number }[] }
expect(embeds[0].color).toBe(resolveColor('#5865F2'))
})Your test runner's mocks
useMockFn(vi.fn), called once in a test setup file, has meocord/testing make every mock
with the runner's own mock function. The runner then treats them as its own: Vitest's clearMocks and mockReset
config and vi.clearAllMocks() reach them, and vi.mocked(interaction.reply) gives Vitest's whole mock API, such as
withImplementation. A generated project's vitest.setup.ts makes this call.
- jest takes
useMockFn(jest.fn), in a file itssetupFileslists. - bun test takes
useMockFn(mock), withmockfrombun:test, in a filebunfig.tomlpreloads. Bun's matchers, such astoHaveBeenCalledWith, read only bun's own mocks, so this is what lets them read MeoCord's. - node:test keeps MeoCord's own mock function: its
mock.fnrecords calls in a shape of its own, whichuseMockFnrefuses.
Call it before any mock is made. Once a mock has been made, a call with another function throws "useMockFn() goes before
any mock is made", whether or not that mock is still in use, since the two kinds would mix. A setup file runs first, so
that is where it goes, ahead of anything that makes a mock when it is imported. What it sets, with useMockFn() or
useStrictMocks(), holds for every test, through vi.resetModules(), jest.resetModules() and Jest's resetModules
config, and the mocks' generated ids keep counting through them.
createMockFn(impl?) makes a stand-alone mock function of the same kind, the runner's own
once useMockFn is called; clearAllMocks() and resetAllMocks() reach it.
isMockFunction(fn) tells a mock from a real function.
Typed values
A mock's mockReturnValue, mockResolvedValue and mockImplementation take any, and its mock.calls and
mock.results read as any. To have them checked against the function they mock, merge typedValues: true into
MockTypeOptions, in a declaration file the tests compile with:
// src/types/meocord-testing.d.ts
import 'meocord/testing'
declare module 'meocord/testing' {
interface MockTypeOptions {
typedValues: true
}
}Each mock then takes only what its function returns, resolves to or is, and reads its own arguments and results.
mockResolvedValue(undefined) stays allowed, since a mock's answers resolve to undefined by default, and an
overloaded method, such as guild.members.fetch, takes what any of its overloads gives. A partial fake is refused:
cast it where it is intended:
it('take only what the mocked function gives', async () => {
const guild = createMockGuild()
const member = createMockMember({ guild })
// One of fetch's overloads resolves to a member
guild.members.fetch.mockResolvedValue(member)
// @ts-expect-error: a partial fake is refused
guild.members.fetch.mockResolvedValue({ id: member.id })
// Cast it where it is intended
guild.members.fetch.mockResolvedValue({ id: member.id } as GuildMember)
expect(await guild.members.fetch(member.id)).toEqual({ id: member.id })
})A project whose tests compile as both ES modules and CommonJS declares it in a .d.ts and a .d.cts. 5.0 types the
values by default.
Resetting between tests
clearAllMocks() forgets what every mock from meocord/testing has recorded.
resetAllMocks() also undoes what a test told them, back to how each was created:
it('clears what mocks recorded, and resets what a test told them', async () => {
const client = createMockClient()
const notify = createMockFn().mockReturnValue('sent')
client.users.fetch.mockRejectedValue(new Error('Unknown User'))
notify()
// Calls are forgotten; behaviour a test set stays
clearAllMocks()
expect(notify.mock.calls).toEqual([])
expect(notify()).toBe('sent')
// Behaviour goes back to how each mock was created, the defaults above included
resetAllMocks()
expect(notify()).toBeUndefined()
await expect(client.users.fetch('1')).resolves.toBeDefined()
})What a mock holds outside its methods stays: an interaction already answered stays replied, and a deleted message
stays deleted. Make a fresh mock in each test, or in beforeEach, rather than one at a spec's top level.
Both reach each of MeoCord's own mocks the next time it is used: called, read through fn.mock or a matcher, or set.
So an array read before the reset, as in const calls = fn.mock.calls, keeps its entries until the mock is next used,
then empties in place; reading fn.mock.calls again sees the reset at once. MeoCord's own mocks don't stay in memory
once a test drops them. With useMockFn(vi.fn), Vitest holds each of its mocks until the test yields, so a test making
thousands of mock interactions in one loop yields between batches, with
await new Promise(resolve => setTimeout(resolve, 0)).
A generated project resets after every test from vitest.setup.ts, as The testing module
shows. A project without it gets the same by adding that file and setupFiles: ['./vitest.setup.ts'] to its
vitest.config.ts.
Under Vitest, its own mockReset puts a mock back to how it was created, so its config works too. Under jest and
bun, a runner's mockReset drops a mock's starting behaviour, and with it what MeoCord's mocks do, such as an
interaction refusing a second reply. Reset there with resetAllMocks(), which puts that behaviour back, and leave
jest's resetMocks off.
Discord's errors
createDiscordError(code) builds the DiscordAPIError discord.js throws, for a mock
to reject with:
- 10062: the three seconds to answer passed;
- 40060: the interaction was already acknowledged;
- 50001: missing access;
- 50027: the fifteen-minute token has expired.
respond() passes the error on to the handler, and getResponse keeps the refused call,
with its error, without counting it as sent:
it('reject with the errors discord.js throws, which getResponse records', async () => {
const interaction = createMockInteraction(ButtonInteraction, { customId: 'late' })
// 10062: the three seconds to answer passed
interaction.update.mockRejectedValueOnce(createDiscordError(10062))
await expect(respond(interaction).send('Refreshed.')).rejects.toBeInstanceOf(DiscordAPIError)
// The refused call stays in calls, with its error, and nothing counts as sent
expect(getResponse(interaction)).toMatchObject({
sent: false,
calls: [{ method: 'update', error: { code: 10062 } }],
})
})A manager's fetch(id) finds or makes the item it's asked for, so a test of an ID that isn't a member, or of a user
that doesn't exist, rejects the fetch with Discord's code:
guild.members.fetch.mockRejectedValue(createDiscordError(10007)) for a member, and
message.client.users.fetch.mockRejectedValue(createDiscordError(10013)) for a user. A typed message param that names
that ID is then refused, as "is not a member of this server" or "no user has the ID …". Use mockRejectedValue rather
than mockRejectedValueOnce: a message naming several IDs fetches them together, then one by one when that fails. A
mention never reaches the fetch, since a member it names comes from the message's mentions.
Gotchas
- A read-only property can't be assigned after creation. TypeScript refuses
modal.customId = …on aModalSubmitInteraction, as discord.js declares it read-only. Set it in the overrides, where a misspelling is caught too. - In a generated project, a MeoCord mock you configure once is reset after the first test.
vitest.setup.tsresets MeoCord's mocks after every test, andclearMocksclears your ownvi.fn(). Set return values in the test that relies on them, or inbeforeEach. - A command's options aren't there by default. A mock
ChatInputCommandInteractionhas no options until you giveoptions: createChatInputOptions({ … })in its overrides, or assign it afterwards. - In default mode,
reply,deferReply,updateanddeferUpdateresolve toundefined, though their types sayInteractionResponse, and the first call from a test's or an app's code warns. A test that assertsLogger.warnwas never called fails on that warning. CalluseStrictMocks(), which resolves them to a mock response that runs its collector, or assert on the warnings the test expects. - A collector isn't moved by fake timers. discord.js times it with
node:timers. End it withmax,stop()or a dispatched answer, not by advancing the clock. - A test that dispatches and also emits delivers twice.
dispatch()already delivers a component no route takes, a message and a reaction to the mock client's listeners, under strict mocks. Emit on the client only whatdispatchdoesn't send. useStrictMocks()goes before the first mock. Called once a mock exists, it throws "useStrictMocks() goes before any mock is made: …". Call it in the test setup file, not inside a test or after a mock made at a spec's top level.
Next steps
- Invoke and dispatch: running handlers with these inputs.
- Testing recipes: themes, guards, cooldowns and failure paths under test.
- Message commands: the typed params a mock server's caches feed.