Testing@rhythmjs/testing
API reference
Every export of the four subpaths: @rhythmjs/testing/rhythm, /router, /cli, and /ws. There is no root barrel export.
On this page
@rhythmjs/testing/rhythm#
function mockModule<TExports extends object>(values: TExports): Rhythm<TExports>;
function withMockContext(app: Mountable, values: object | undefined): Mountable;
function runMiddleware<TContext extends object>(
middleware: Middleware<TContext>,
ctx: TContext,
): Promise<MiddlewareRun<TContext>>;mockModule(values)#- A Rhythm module named
mockwhose startup context isvalues, copied verbatim. Pull it into an app withinclude(mockModule(values), pick). There is no dispose hook: a fake that needs cleanup is cleaned up by the test that created it. withMockContext(app, values)#- Wraps any mountable (app, router, cli, ws) so
valuesare assigned onto every call's input.Rhythmmerges input over its startup context, so mocks replace real startup values.valuesmay beundefined(no-op). Typed as a plainMountable, so cast the context it returns. runMiddleware(middleware, ctx)#- Invokes the middleware with your context and a stub
next()that records being called and resolves immediately. MiddlewareRun<TContext>#- { ctx: TContext; nextCalled: boolean }: the mutated context and whether the chain continued.
MockContext<TApp>#- The startup fields plus declared input an app accepts mocks for.
@rhythmjs/testing/router#
function createTestClient<TApp extends Mountable>(
app: TApp, // a Rhythm app or a RhythmRouter that accepts the HTTP context
options?: TestClientOptions<Mockable<TApp>>,
): TestClient;
function runHttpMiddleware<TExtras extends object = {}>(
middleware: Middleware<RhythmHttpContext & TExtras>,
request?: string | Request,
extras?: TExtras,
): Promise<HttpMiddlewareRun<RhythmHttpContext & TExtras>>;createTestClient(app, options?)#- Accepts a Rhythm app or a bare
RhythmRouterand returns verb helpers overtoFetchHandler.options.baseUrlresolves relative paths (defaulthttp://localhost).options.contextis aPartialof the app's startup context and declared input (minus the HTTP base fields), assigned onto every request's context, so mocks replace real startup values. It fails to type-check when the app needs input the client cannot provide. TestClient#fetch(input, init?)plusget/head/post/put/patch/delete, each(path, options?) => Promise<Response>. There is noteardown(): close any resource you created yourself inafterAll.TestRequestOptions#- { headers?; body?; json? };
jsonserializes the value and setscontent-type: application/jsonunless you set one yourself, and takes precedence overbody.TestRequestHeaders,TestRequestBody, andTestRequestInitalias the corresponding fetch constructor parameter types. runHttpMiddleware(middleware, request?, extras?)#- Builds a real HTTP context with
createHttpContextfrom a path orRequest(defaulthttp://localhost/), assignsextrasonto it, runs the middleware, and returnsHttpMiddlewareRun. To test a router, passmount(router). HttpMiddlewareRun#- { ctx; nextCalled: boolean; response: Response }:
responseis the context's response rendered withtoResponse.
@rhythmjs/testing/cli#
function createCliRunner<TApp extends Mountable>(
app: TApp, // a Rhythm app that mounts a cli, or a RhythmCli
options?: CliRunnerOptions<Mockable<TApp>>,
): CliRunner;
interface CliRunner {
run(argv: string | string[]): Promise<CliRunResult>;
}
interface CliRunResult {
stdout: string;
stderr: string;
exitCode: number;
}createCliRunner(app, options?)#- Runs the app through
toCliHandler, with output captured instead of written to real stdio.options.contextis aPartialof the app's startup context and input (minus the cli base fields), assigned onto every run's context so mocks win over real values. CliRunner.run(argv)#argvis a command string (trimmed and split on whitespace) or an argv array. Flags are parsed only when the cli useswithParsedArgv(). An unknown command exits with2, a thrown error with1, andctx.fail(message, code)with your code.CliRunResult#- { stdout: string; stderr: string; exitCode: number }: the captured text, newlines included.
@rhythmjs/testing/ws#
function upgradeWs<Data extends object = Record<string, string>>(
ws: RhythmWs,
request: string | Request,
): Promise<WsUpgradeResult<Data>>;
function mockWs<Data extends object = Record<string, string>>(data: Data): MockWs<Data>;
function fireOpen(peer: MockWs): void | Promise<void>;
function fireMessage(peer: MockWs, data: string | Uint8Array | object): void | Promise<void>;
function fireClose(peer: MockWs, code = 1000, reason = ""): void | Promise<void>;
function fireDrain(peer: MockWs): void | Promise<void>;upgradeWs(ws, request)#- Mounts the
RhythmWsin a freshRhythmapp and runs the request throughtoFetchHandlerwith a recording server. A string becomes a request with theupgrade: websocketheader implied. Middleware, the route'supgradeandheadersall run for real. WsUpgradeResult<Data>#- { upgraded; response; data; headers; peer }:
upgradedis true when the route calledserver.upgrade;responseis the rejection or unmatched response,nullwhen accepted;datais thews.dataattached andheaderswhat the route passed to the upgrade (bothnullwhen not upgraded);peeris aMockWsbuilt ondata, ornull. mockWs(data)#- A recording
ServerWebSocketstand-in:sent,published,topics,closed, andterminatedcapture everything handlers do;send/publishreturn byte counts;close/terminateflipreadyStateto 3.data,readyState,remoteAddress(127.0.0.1), andisSubscribedround out the surface handlers touch. fireOpen / fireMessage / fireClose / fireDrain#- Take only the peer and invoke the matching handler of the
websocketobject from@rhythmjs/ws, which dispatches throughws.datato the matched route. The peer must come fromupgradeWs.fireMessagepasses strings through, wrapsUint8Arrayin aBuffer, and JSON-serializes any other object. Alwaysawaitthem.