Skip to content

Connectum API Reference / @connectum/auth / testing / withAuthContext

Function: withAuthContext() ​

withAuthContext<T>(context, fn): Promise<T>

Defined in: packages/auth/src/testing/with-context.ts:36

Run a function with a pre-set AuthContext.

Sets the provided AuthContext in AsyncLocalStorage for the duration of the callback. Useful for testing handlers that call getAuthContext().

The context is scoped to the callback, not to a value it returns. For an async function* handler, iterate the generator inside fn: a generator created inside fn but consumed after fn has returned does not see the context.

Type Parameters ​

T ​

T

Parameters ​

context ​

AuthContext

Auth context to set

fn ​

() => T | Promise<T>

Function to execute within the context

Returns ​

Promise<T>

Return value of fn

Example ​

Test a handler that reads auth context

typescript
import { withAuthContext, createMockAuthContext } from '@connectum/auth/testing';
import { getAuthContext } from '@connectum/auth';

await withAuthContext(createMockAuthContext({ subject: 'test-user' }), async () => {
  const ctx = getAuthContext();
  assert.strictEqual(ctx?.subject, 'test-user');
});