Skip to content
GitHub

TestingModule

class in meocord/testing Since 4.0.0

class TestingModule

A compiled testing module, which runs handlers as the bot does and resolves the classes it built.

Use invoke to run a handler you name, dispatch to send an input through the bot's routing, and emit for a gateway event. getResponse then reports what a handler sent.

Examples

TypeScript
import { expect } from 'vitest'

@Controller()
class TicketController {
  @Command('ticket/{id}/close', CommandType.BUTTON)
  async close(interaction: ButtonInteraction, { id }: { id: string }) {
    await respond(interaction).send(`Ticket ${id} closed.`)
  }
}
const module = MeoCordTestingModule.create({ controllers: [TicketController] }).compile()
const { handlers } = await module.dispatch(createMockInteraction(ButtonInteraction, { customId: 'ticket/7/close' }))
expect(handlers).toEqual([{ controller: TicketController, method: 'close', ran: true }])

Members

constructor

new TestingModule(
  container: unknown,
  controllers?: unknown,
  eventClasses?: unknown,
  providers?: unknown,
  order?: unknown,
  messageOptions?: unknown,
  lifecycle?: unknown,
  constructed?: unknown,
  appWarnUnanswered?: unknown,
  services?: unknown,
  shutdownTimeout?: unknown,
  app?: unknown,
  eventFallback?: unknown,
  botLifecycle?: unknown,
  hooks?: unknown,
)

A module is made by MeoCordTestingModule.create(…).compile() or MeoCordTestingModule.fromApp(…).compile(), not by hand. The parameters are what MeoCord builds it from, so they are typed unknown.

Parameters

NameTypeSince
containerunknown
controllers?unknown4.1.0
eventClasses?unknown4.1.0
providers?unknown4.1.0
order?unknown4.1.0
messageOptions?unknown4.1.0
lifecycle?unknown4.1.0
constructed?unknown4.1.0
appWarnUnanswered?unknown4.1.0
services?unknown4.1.0
shutdownTimeout?unknown4.1.0
app?unknown4.2.3
eventFallback?unknown4.3.0
botLifecycle?unknown4.3.0
hooks?unknown4.3.0

themeCache Since 4.1.0

get themeCache(): ThemeCache

The module's ThemeCache: the instance its classes inject, holding what themeFor, or overrideThemeFor, looked up in this module's calls. Clear a result to have the next call look it up again. Each module has its own.

close Since 4.1.0

close(): Promise<void>

Runs the onShutdown hooks of every class and provided value the module has constructed, once, as the bot does when it stops: one at a time, in reverse, so a class stops before the classes and providers it uses. A factory's value, such as a connection pool init() made, is closed after everything that injects it, whether or not init({ ready: true }) ran. Nothing is constructed just to be shut down. Every hook runs even when one fails. Calling it again does nothing more.

Once init({ ready: true }) is asked, it follows the bot's rules for the onReady hooks: no onReady starts after close() is called, and a unit whose onReady hasn't settled, such as one still running, or never started because close() came first, gets no onShutdown, nor does anything that depends on it. An onReady that failed has settled. Without init({ ready: true }), it shuts down every unit the module made.

It first gives up the theme read outside calls, if init({ ready: true }) made it this module's; reads outside calls then return MeoCord's defaults until another module or app is ready.

A stopped bot runs nothing more. Once close() is called, a module still runs what dispatch, invoke and emit are given, against services shut down, or shutting down, and warns once that it is closed, so a close() in the wrong place shows. A call made before close() that still waits for the init() it ended doesn't start, as a call the bot drops when it stops: it resolves with ran false, or 0 for emit, and the error "The bot stopped before this call started.". A get() afterwards returns what was shut down silently. A call or a get() that makes an instance with an onShutdown only then warns, naming it, since nothing shuts that down; one that needs a factory's value the init() that close() ended didn't reach fails, naming it, and the factory doesn't run.

The cooldown store and what it injects shut down last, in the same sequence as the bot's. When any of them has an onShutdown, the calls invoke, dispatch and emit have under way finish first, then the store operations they started, so the store's last writes still reach it. A call that calls close() itself, such as a command handler for an owner-only shutdown, isn't waited for, as the bot's stop() doesn't wait for a handler that awaits it. The module stops waiting for the whole sequence after its shutdownTimeout, 10 seconds unless set, and logs that it did. Give a test whose fake store never answers, or whose onShutdown never settles, a short shutdownTimeout.

A close() while init() makes the providers waits for the factory under way at most shutdownTimeout; past it, it warns, naming the factory, and shuts down without it. init() makes nothing after that factory. A value the factory returns later is shut down once it arrives and close() is done, by its own onShutdown, within shutdownTimeout, and a failure of it is logged; after init({ ready: true }), only if neither it nor what it injects has an onReady, which never ran. What it injects is shut down already, so its onShutdown may find that closed.

A close() while init({ ready: true }) runs the onReady hooks waits for them first, within the same shutdownTimeout. An onReady still running once only the hooks' share of it is left is named in a warning, and its class gets no onShutdown, as above. One that calls close() itself isn't waited for. A close() called while an onShutdown hook of this close runs, by the hook or by work it started, awaited or not, gets a promise that resolves at once: the close it asks for is the one running the hook. One called after the hook has returned waits for the whole close.

Returns

Promise<void>

Once every hook has run. Rejects with the error of a hook that failed, or an AggregateError naming each when several did.

Examples

TypeScript
import { expect } from 'vitest'

const POOL = createToken<object>('Pool')
const closed: string[] = []
@Service()
class Notes {
  constructor(@Inject(POOL) readonly pool: object) {}
  onShutdown() {
    closed.push('notes')
  }
}
const module = await MeoCordTestingModule.create({
  providers: [{ provide: Notes, useClass: Notes }, { provide: POOL, useFactory: async () => ({ onShutdown: () => closed.push('pool') }) }],
})
  .compile()
  .init()
module.get(Notes)

await module.close()

expect(closed).toEqual(['notes', 'pool'])

dispatch Since 4.1.0

dispatch(input: Interaction | Message): Promise<DispatchedCall>

dispatch(
  reaction: MessageReaction | PartialMessageReaction,
  options: { user: User | PartialUser; action?: ReactionHandlerAction },
): Promise<DispatchedCall>

Sends an interaction, a message or a reaction through the bot's own dispatch: routed over the module's controllers and its app's message options exactly as the bot routes it, then run through the full pipeline of each handler it reaches. What the user is sent is sent to the mock, as the bot sends it: the handler's answer, a usage reply, or the built-in fallback's answer to an error no filter handles. Inputs the bot skips, such as a message from a bot, reach nothing. The module waits for its observers.

dispatch tests what the bot does with an input: which handler it reaches, with what params, and what the user sees. To test one handler you name, whatever would route to it, use invoke.

Under useStrictMocks(), a component or modal no route takes, on a client from createMockClient with interactionCreate listeners, such as a collector's, is delivered to those listeners after MeoCord's dispatch, in the order they were attached, as the gateway delivers it; MeoCord answers that no handler matched only if none of them answered. Dispatch waits for what each listener returns, then one turn of the event loop, never the bot's 1.5 seconds; an answer a listener sends only after a timer of its own isn't waited for. A component a route takes is not delivered to them, unlike on a bot. Dispatch alone delivers it: calling client.emit('interactionCreate') as well delivers it twice. What a listener throws or rejects with rejects dispatch once MeoCord has answered.

Under useStrictMocks(), on a client from createMockClient, a message or a reaction reaches its client's messageCreate, messageReactionAdd or messageReactionRemove listeners too, routed or not, with discord.js's arguments, as the gateway delivers it: those attached before routing starts, once the route has run to its first await, so a collector a handler starts takes the next message, not the one that started it. Dispatch alone delivers it: calling client.emit with the same event as well delivers it twice, and emit applies nothing to a reaction. A dispatched reaction is a normal one, never a burst: its listeners get { type: ReactionType.Normal, burst: false }.

A reaction is applied to its message first, as the gateway applies it, by discord.js's own code. An add caches it on message.reactions and counts the user into its users, count and countDetails. Where its message doesn't cache it, the add starts it from none, users and me too, unless its state is the test's: a count, countDetails, me or users the test gave before its first dispatch, or a count or countDetails set after one. The add then counts on from what is there, count and countDetails apart, as discord.js keeps them. A remove takes the user out of users, and out of the count unless the user is the bot and me is set, as discord.js leaves that to the bot's own REST call; once neither users nor count are left the reaction leaves message.reactions. A remove of a reaction its message doesn't cache is delivered and changes nothing: a real client without Partials.Reaction emits nothing for it, and dispatch delivers it all the same, so a test doesn't show that a bot needs the partial. A partial reaction, its count null, is delivered as it is. A reaction on a real Client, its own or its message's, is routed as any other, the bot's own told apart by user.bot since the client has no user before login, and nothing is applied or delivered. Dispatch waits for the listeners as for a component, and what one throws or rejects with rejects it.

Parameters

NameType
inputInteraction | Message

An interaction or a message; or a reaction, with the user who reacted and whether they added it, ReactionHandlerAction.ADD unless given.

Returns

Promise<DispatchedCall>

Every handler reached, in the order it ran, whether any ran, and the first error a call ended with. An error the fallback answers as the user's own outcome resolves: a usage reply, an unknown command, or a guard's, a cooldown's, a validation's or a UserError's refusal, as the fallback answers each for an interaction or a message. Any other error no filter handles, and what a client's listener the input was delivered to threw, rejects the call once the fallback has answered and every handler has run: with that error, or an AggregateError when there are several.

Examples

TypeScript
import { expect } from 'vitest'

@Controller()
class CardController {
  @Command('card/summary/{id}', CommandType.BUTTON)
  async summary(interaction: ButtonInteraction, { id }: { id: string }) {
    await respond(interaction).send(`Card ${id}`)
  }
}
const module = MeoCordTestingModule.create({ controllers: [CardController] }).compile()
const interaction = createMockInteraction(ButtonInteraction, { customId: 'card/summary/7' })

const { handlers } = await module.dispatch(interaction)

expect(handlers).toEqual([{ controller: CardController, method: 'summary', ran: true }])

Parameters

NameType
reactionMessageReaction | PartialMessageReaction
options{ user: User | PartialUser action?: ReactionHandlerAction }
options.userUser | PartialUser
options.action?ReactionHandlerAction

Returns

Promise<DispatchedCall>

Every handler reached, in the order it ran, whether any ran, and the first error a call ended with. An error the fallback answers as the user's own outcome resolves: a usage reply, an unknown command, or a guard's, a cooldown's, a validation's or a UserError's refusal, as the fallback answers each for an interaction or a message. Any other error no filter handles, and what a client's listener the input was delivered to threw, rejects the call once the fallback has answered and every handler has run: with that error, or an AggregateError when there are several.

Examples

TypeScript
import { expect } from 'vitest'

@Controller()
class CardController {
  @Command('card/summary/{id}', CommandType.BUTTON)
  async summary(interaction: ButtonInteraction, { id }: { id: string }) {
    await respond(interaction).send(`Card ${id}`)
  }
}
const module = MeoCordTestingModule.create({ controllers: [CardController] }).compile()
const interaction = createMockInteraction(ButtonInteraction, { customId: 'card/summary/7' })

const { handlers } = await module.dispatch(interaction)

expect(handlers).toEqual([{ controller: CardController, method: 'summary', ran: true }])

emit Since 4.1.0

emit<E extends keyof ClientEvents>(
  event: E,
  ...args: ClientEvents[E]
): Promise<EmitResult>

Emits a client event to the module's @On and @Once handlers, through the pipeline the app runs them in: the global guards of the module's app, then each handler's own. As on the bot, every instance the module runs lifecycle hooks on, the cooldown store aside, receives it: the controllers and services, what they and the stages inject, and each provided class or value. A @Once handler handles only the first event, as it would on a client.

On a bot, a guard's GuardDeniedError is logged and the event skipped, and a handler's UserError is logged and, when the event carries a message, answered as a reply to it. With eventFallback: true the module does the same, with the bot's own event fallback. Without it both reject emit as any error does, so a test checks them with rejects, and a warning says once that 5.0 answers them as the bot does.

Parameters

NameType
eventE

The client event, such as 'guildMemberAdd'.

...argsClientEvents[E]

The event's arguments, typed from discord.js's ClientEvents.

Returns

Promise<EmitResult>

How many handlers ran. Rejects once every handler has settled if any threw, a guard's GuardDeniedError and a handler's UserError included unless the module has eventFallback: true: with that error when one handler failed, or an AggregateError of them when several did.

Examples

TypeScript
import { expect } from 'vitest'

@Controller()
class WelcomeController {
  @On('guildMemberAdd')
  async greet(member: GuildMember) {
    await member.send('Welcome!')
  }
}
const module = MeoCordTestingModule.create({ controllers: [WelcomeController] }).compile()
const member = createMock<GuildMember>()

const { ran } = await module.emit('guildMemberAdd', member)

expect(ran).toBe(1)

get

get<T>(token: ProviderToken<T> | ServiceIdentifier<T>): T

Resolves an instance from the module, as the bot would inject it.

After close, it returns what close() shut down without a word, so a test can read how it ended. One it makes only then, such as a listed service an init() that close() ended did not make, is shut down by nothing; when it has an onShutdown, the get() that makes it warns, naming it, as dispatch, invoke and emit do.

Parameters

NameType
tokenProviderToken<T> | ServiceIdentifier<T>

A controller, a provided token, or another bound class.

Returns

T

The instance, with its dependencies and overrides applied.

Throws

  • When the instance depends on a factory that returns a promise and init() has not made its value: it has not run, or a close() ended it first. And when it depends on a factory init() didn't reach before a close() ended it: that factory doesn't run after close().

init Since 4.1.0

init(options?: TestingModuleInitOptions): Promise<this>

Resolves the module's useFactory providers, awaiting those that return a promise, in dependency order. invoke, dispatch and emit call it first; call it yourself before get resolves anything that depends on an asynchronous factory. Calling it again does nothing more.

With { ready: true }, it then runs every onReady hook once, as the bot does once it is online: one at a time, each class after the classes and providers it injects, the observers' last, then, under useStrictMocks(), a class only a stage or the presenter injects, as in the bot. Every hook runs even when one fails. Pair it with close, which runs the onShutdown hooks. With @MeoCord({ waitForReady: true }), a dispatch, invoke or emit made while they run waits for the hooks of the classes it uses, as the bot's calls do.

Ready, the module's app theme is also the one useTheme() reads outside any call, as a bot's is once it is online, unless another module or app in the process was ready first: that one keeps it, and this module's theme reaches its own calls only. close gives it up; nothing takes it over.

A close while it makes the providers ends it, as a stop ends a bot's start: the factory under way finishes, and nothing after it is made, no other factory and no listed service, and no onReady hook runs. It resolves all the same. A factory that settles after close() stopped waiting for it has its value shut down once it arrives and close() is done, and init() resolves after that.

Parameters

NameTypeDefault
options?TestingModuleInitOptions

ready to also run the onReady hooks, with the client and primary to pass them.

options.ready?| boolean | { client?: Client<true> primary?: boolean }

false

Also runs every onReady hook, once, in dependency order, as the bot does once it is online. true hands each hook a mock client from createMockClient and { primary: true }; an object sets either.

Returns

Promise<this>

The module, once every factory has made its value and every onReady hook asked for has run. Rejects with the error of a factory or a hook that failed, or an AggregateError of the hooks when several did.

Examples

TypeScript
import { expect } from 'vitest'

const DATABASE = createToken<{ connected: boolean }>('Database')
@Service()
class NotesStore {
  loaded = false
  constructor(@Inject(DATABASE) private readonly db: { connected: boolean }) {}
  onReady() {
    this.loaded = this.db.connected
  }
}
const module = await MeoCordTestingModule.create({
  providers: [
    { provide: NotesStore, useClass: NotesStore },
    { provide: DATABASE, useFactory: async () => ({ connected: true }) },
  ],
})
  .compile()
  .init({ ready: true })

expect(module.get(NotesStore).loaded).toBe(true)
await module.close()

invoke Since 4.1.0

invoke<C extends new (...args: any[]) => unknown, M extends HandlerName<C>>(
  controller: C,
  methodName: M,
  ...args: HandlerArgs<C, M>
): Promise<InvocationResult>

Runs a handler through the same pipeline dispatch runs: @Defer's acknowledgement, the global guards of the module's app, then the handler's own, in order and once each; then the interceptors, the app's first, around validation, pipes, cooldowns and the handler; all inside the handler's exception filters. Guards resolve from this module, so overrideGuard stubs apply and guards that inject ExecutionContext receive it. overrideInterceptor and overrideFilter stubs apply the same way.

Calling the controller method directly runs its guards but no interceptors, validation or filters; invoke is the way to test everything dispatch runs around a handler.

invoke tests one handler you name, and an error no filter handles rejects the call. That includes the errors the bot answers the user with: a guard's GuardDeniedError, a UserError and a CooldownError reject invoke, where dispatch resolves { ran, error } and sends the answer. To test what the bot does with an input, which handler it reaches and what the user is sent, use dispatch.

Parameters

NameType
controllerC

A controller of the module: one given to create, or one of the app fromApp built it from.

methodNameM

The handler method's name.

...argsHandlerArgs<C, M>

The arguments dispatch would pass: the interaction, message or reaction, then the handler's params. With an interaction alone, the params are built as dispatch builds them: a command's or an autocomplete's options, or the handler's customId params with a modal's fields or a select menu's choices. An interaction's customId or command name must be one dispatch routes to the handler, ranking every handler of the module as the bot does; a mock built without one is not checked. An autocomplete is checked by its command path and its focused option: one dispatch gives to another @Autocomplete handler, or to none, is refused under useStrictMocks(), and otherwise warned about once and run. With a message alone, a patterned @MessageHandler gets the params its pattern captures from the content, after the prefix of the module's app, with typed params resolved as dispatch resolves them, from the message's guild caches first. A message whose content isn't a string, as a mock's without useStrictMocks(), gets {}. Under strict mocks a message has empty content, and a patterned handler rejects it, as dispatch runs no handler for a message with no text: give the mock the content the handler takes. A word that is not a value of its type, and a prefixed message that names the command but leaves out a param, go through the handler's filters as a MessageUsageError, as dispatch answers them. An @On or @Once handler no route reaches runs as emit runs it, as an event with the arguments given, under useStrictMocks(); without strict mocks it runs as its first argument's type, and invoke warns once where that differs.

Returns

Promise<InvocationResult>

Whether the handler ran, and the error a filter handled, if any. Rejects with an error no filter handles, or with the error a filter throws: the built-in fallback, which answers such errors in the bot, does not run here. Rejects before running anything with an interaction or a message the handler's route does not match, naming both, and under useStrictMocks() with such an autocomplete. Given fewer arguments than the handler declares, with a first that is neither an interaction nor a message, such as a reaction without its ReactionEvent, it rejects under useStrictMocks(), and otherwise warns once and runs the handler.

Examples

TypeScript
import { expect } from 'vitest'

@Guard()
class ModeratorGuard implements GuardInterface {
  canActivate() {
    return false
  }
}
@Guard()
class OwnerGuard implements GuardInterface {
  canActivate(): boolean {
    throw new GuardDeniedError('Only the server owner can kick.')
  }
}
@Controller()
class ModerationController {
  @Command('ban', CommandType.SLASH)
  @UseGuard(ModeratorGuard)
  async ban(interaction: ChatInputCommandInteraction) {
    await respond(interaction).send('Banned.')
  }

  @Command('kick', CommandType.SLASH)
  @UseGuard(OwnerGuard)
  async kick(interaction: ChatInputCommandInteraction) {
    await respond(interaction).send('Kicked.')
  }
}
const module = MeoCordTestingModule.create({ controllers: [ModerationController] }).compile()
const interaction = createMockInteraction(ChatInputCommandInteraction)

// A guard that returns false
const { ran } = await module.invoke(ModerationController, 'ban', interaction)

expect(ran).toBe(false)
expect(interaction.reply).not.toHaveBeenCalled()
// In a module whose app sets @MeoCord({ answerDenied: true }), that false rejects with GuardDeniedError instead, as below

// A guard that throws GuardDeniedError, or a handler that throws UserError
await expect(module.invoke(ModerationController, 'kick', interaction)).rejects.toThrow(GuardDeniedError)

// dispatch answers it as the bot does, and resolves with the outcome
const outcome = await module.dispatch(createMockInteraction(ChatInputCommandInteraction, { commandName: 'kick' }))
expect(outcome.ran).toBe(false)
expect(outcome.error).toBeInstanceOf(GuardDeniedError)

See also