Skip to Content
Runlane
Build with RunlaneDevelop and test

Test tasks

Test public task behavior with an isolated runtime and controlled time.

Test through Runlane's public API: trigger the task, execute it, and assert the domain effect or stored result. Use createTestLane() for process memory without dev or filesystem access. Give parallel tests distinct names to keep their state separate.

Run the complete example

Create a Vitest test file in your application:

src/tasks/send-email.test.ts
import { createRunlane, queue, RunStatus, task } from '@runlane/core'
import { createTestLane } from '@runlane/lane-local'
import { createControlledClock } from '@runlane/testing'
import { expect, test } from 'vitest'
import * as z from 'zod'

test('sends a welcome email', async () => {
  // Given
  const sentEmails: string[] = []
  const sendWelcomeEmail = task({
    id: 'email.send-welcome',
    schema: z.object({ email: z.email() }),
    run({ email }) {
      sentEmails.push(email)
    },
  })
  const runlane = createRunlane({
    lane: createTestLane(),
    queues: [queue({ name: 'default', default: true })],
    tasks: { sendWelcomeEmail },
  })

  // When
  const { run } = await runlane.trigger(runlane.tasks.sendWelcomeEmail, {
    email: 'ada@example.com',
  })
  await runlane.drain()
  const storedRun = await runlane.runs.get(run.id)

  // Then
  expect(sentEmails).toEqual(['ada@example.com'])
  expect(storedRun?.status).toBe(RunStatus.Succeeded)

  await runlane.close()
})

test('controls time without sleeping', () => {
  // Given
  const clock = createControlledClock({
    startAt: new Date('2026-01-01T00:00:00.123Z'),
  })

  // When
  clock.advanceBy('5m')

  // Then
  expect(clock.now()).toEqual(new Date('2026-01-01T00:05:00.123Z'))
})

The first test follows Given–When–Then:

  1. Define the task and create a fresh runtime.
  2. Trigger the registered task handle.
  3. Drain currently due work.
  4. Assert the domain effect.
  5. Assert only the run state needed by the contract.

Close the runtime at the end. Use your test framework's cleanup hook if an assertion can stop execution before the explicit close.

Control time instead of sleeping

createControlledClock() changes time only when the test calls advanceBy(). Use it when retries, releases, schedules, leases, or token timeouts depend on time.

Runlane reads time in two places: the runtime and storage. Storage time decides when saved work is due. Pass the controlled clock to the runtime and its now function to the test lane:

src/tasks/controlled-time.test.ts
import { createRunlane, queue, WaitTokenStatus } from '@runlane/core'
import { createTestLane } from '@runlane/lane-local'
import { createControlledClock } from '@runlane/testing'
import { expect, test } from 'vitest'

test('a token times out on controlled time', async () => {
  // Given
  const clock = createControlledClock({ startAt: new Date('2026-01-01T00:00:00.123Z') })
  const lane = createTestLane({ clock: () => clock.now() })
  const runlane = createRunlane({ clock, lane, queues: [queue({ name: 'default', default: true })], tasks: [] })
  const { token } = await runlane.wait.createToken({ timeout: '1d' })

  // When
  clock.advanceBy('2d')
  await runlane.runMaintenanceOnce()

  // Then
  expect((await runlane.wait.getToken(token.id))?.status).toBe(WaitTokenStatus.TimedOut)
  await runlane.close()
})

Use a start time with milliseconds. It catches precision bugs that a whole-second clock can hide.

Advancing the clock does not run work by itself. Call the relevant maintenance or worker method after the time change.

Keep tests isolated

  • Create the lane and runtime inside the test or a fresh fixture, then close the runtime.
  • Same-name test lanes share runs and work signals, even across module copies. Their store is released after the last handle closes. A new handle then gets fresh memory. Give tests separate names when they need isolation, for example createTestLane({ name: 'email-retry' }). Use one name deliberately when testing multiple runtimes over shared state. Pass the same clock function to each handle; a different clock rejects with configuration_invalid. Test stores are separate from dev-hosted local stores.
  • Use drain() to execute currently due work, or executeNext() for one attempt. Do not start a delivery worker when the test controls execution this way.
  • Do not share mutable provider state across cases.
  • Use a unique Runlane environment for shared external infrastructure.
  • Assert domain behavior before internal lifecycle detail.
  • Use real Postgres or SQS-compatible tests for provider timing and redelivery boundaries.

Test the failures that matter

Add cases for the behavior your task uses:

  • invalid payload and output;
  • retry exhaustion and non-retryable failure;
  • release and resume;
  • cancellation and worker shutdown;
  • durable-step replay;
  • duplicate idempotency keys;
  • queue concurrency;
  • wait-token completion and timeout.

Avoid tests that call private transition helpers. Public behavior survives refactors and proves the integration users depend on.

Check one controlled replay

Install the assertion's optional peers as development dependencies alongside @runlane/core:

pnpm add -D @runlane/local-adapters @runlane/testing

Import assertReplaySafe from @runlane/core/testing. It creates an isolated Local runtime and controlled clock, runs your handler, inserts a durable sleep after its first successful return, and replays the same run. It checks two handler entries, stable run identity and saved checkpoints, terminal success, and equal normalized results. It closes the runtime on success or failure. You do not need to build a runtime or clock.

For an existing task:

import { assertReplaySafe } from '@runlane/core/testing'

await assertReplaySafe(sendWelcomeEmail, { payload: { email: 'ada@example.com' } })

The payload uses the task schema's input type. You can omit it when that input accepts undefined. Payload and saved-step transforms keep their normal runtime behavior. The assertion compares raw normalized handler results; it does not apply the task output schema again to saved results.

To detect calls outside saved step callbacks, use the factory overload. Construct the task with the wrapped functions it supplies:

src/tasks/replay.test.ts
import { task } from '@runlane/core'
import { assertReplaySafe } from '@runlane/core/testing'
import { test } from 'vitest'
import * as z from 'zod'

test('saves the email effect before replay', async () => {
  const sent: string[] = []

  await assertReplaySafe(
    ({ send }) =>
      task({
        id: 'email.replay',
        schema: z.string(),
        run(email, { step }) {
          return step.run('send', { output: z.string() }, () => send(email))
        },
      }),
    {
      payload: 'ada@example.com',
      effects: {
        send(email: string) {
          sent.push(email)
          return email
        },
      },
    },
  )
})

Use test doubles for supplied effects. The wrapper preserves each function's argument and result types. A wrapped effect outside an active saved step callback, or repeated on replay, fails with its name and pass number. Catching the error in the handler does not hide the violation. Passing an effect alongside an already-built task cannot replace a function captured by that task's closure; use the factory overload.

This assertion supports otherwise-successful callback-step handlers and one controlled replay. Task-owned suspensions, child workflows, cancellation, and more than two handler entries are unsupported; use the full runtime tests above for those cases. It detects only wrapped effects. Unwrapped filesystem, database, and SDK calls, randomness, and clocks remain undetected. A pass is not proof of arbitrary side-effect safety or provider idempotency after a crash.

The Local and testing peers load only through @runlane/core/testing. Importing @runlane/core does not load them.

Test hook retries

Give storage and the runtime the same controlled clock. drain() waits for due hook callbacks after its run work finishes, without waiting for idle polling timers. Advancing time does not run callbacks by itself.

import {
  contractDefaults,
  createRunlane,
  getRetryDelayMilliseconds,
  queue,
  retryPolicySchema,
  task,
} from '@runlane/core'
import { createTestLane } from '@runlane/lane-local'
import { createControlledClock } from '@runlane/testing'
import { expect, test } from 'vitest'
import * as z from 'zod'

test('retries a completion callback when due', async () => {
  const clock = createControlledClock()
  const attempts: number[] = []
  const work = task({
    id: 'hook-retry',
    schema: z.undefined(),
    run: () => undefined,
    onComplete: (_input, context) => {
      attempts.push(context.hookAttempt)
      if (context.hookAttempt === 1) throw new Error('Try again')
    },
  })
  const runlane = createRunlane({
    clock,
    lane: createTestLane({ clock: () => clock.now() }),
    queues: [queue({ name: 'default', default: true })],
    tasks: { work },
  })
  try {
    const { run } = await runlane.trigger(work)
    await runlane.drain()
    expect(attempts).toEqual([1])
    await runlane.drain()
    expect(attempts).toEqual([1])

    const delay = getRetryDelayMilliseconds(retryPolicySchema.parse(contractDefaults.hooks.retry), 1)
    clock.advanceBy(`${delay}ms`)
    expect(await runlane.drain()).toEqual({ runsExecuted: 0 })
    expect(attempts).toEqual([1, 2])
    expect((await runlane.runs.get(run.id))?.hooks?.status).toBe('done')
  } finally {
    await runlane.close()
  }
})

Hook deliveries do not spend maxRuns. A retryable callback failure with attempts left gets a future retry time, so one drain terminates. A non-retryable failure ends delivery at once. To test exhaustion, advance by getRetryDelayMilliseconds(policy, attempt) and drain for each failed attempt through policy.maxRetries, where policy = retryPolicySchema.parse(contractDefaults.hooks.retry).

On this page