Reference

Testing


@orcher/sdk/testing runs a workflow's code in memory, with no engine and no worker. Tasks are replaced by mocks you configure by task name, and durable timers wait on a test clock that you move forward. It works with any test runner; the samples use Node's built-in node:test.


The Workflow Under Test

1
export const orderWorkflow = workflow({
2
name: 'order',
3
run: async (ctx: WorkflowContext, order: Order): Promise<{ status: string; chargeId?: string }> => {
4
const chargeId = await ctx.executeTask(charge, order);
5
try {
6
await ctx.executeTask(reserveStock, order.orderId);
7
} catch (err) {
8
if (isWorkflowSuspension(err)) throw err;
9
await ctx.executeTask(refund, chargeId);
10
return { status: 'refunded' };
11
}
12
// Send the receipt an hour later.
13
await ctx.sleep(Duration.fromHours(1));
14
await ctx.executeTask(sendReceipt, order.orderId);
15
return { status: 'completed', chargeId };
16
},
17
});

Test Environment

TestWorkflowEnvironment.create() is async. executeWorkflow() takes the reference that workflow({ ... }) returns, or a run function, and the workflow's input. Release the environment with cleanup().

1
import assert from 'node:assert/strict';
2
import { afterEach, beforeEach, describe, it } from 'node:test';
3
import { TestWorkflowEnvironment } from '@orcher/sdk/testing';
4
import { orderWorkflow } from './order';
5
6
describe('order workflow', () => {
7
let env: TestWorkflowEnvironment;
8
9
beforeEach(async () => {
10
env = await TestWorkflowEnvironment.create();
11
});
12
13
afterEach(async () => {
14
await env.cleanup();
15
});

To test a @Workflow class, wrap its run() method in a run function:

1
// A class is not a run function: wrap its run() method.
2
const result = await env.executeWorkflow(
3
(ctx: WorkflowContext, order: Order) => new ChargeOnly().run(ctx, order),
4
{ orderId: '9', amount: 100 },
5
);

Mocking Tasks

Every task the workflow calls needs a mock: a call to a task without one fails with an error naming it. env.mockTask(name) returns a builder:

Builder methodThe mock
.returns(value)Returns value every time
.returnsSequence([a, b, error])Returns each value in turn; an Error in the list is thrown
.throws(error)Throws every time
.withFn(fn)Calls fn(input) and returns what it returns
.resolvesAfter(value, ms) / .rejectsAfter(error, ms)Settles after ms of test-clock time
.spy(fn?)Calls fn if given, otherwise returns undefined
1
it('refunds the charge when stock cannot be reserved', async () => {
2
env.mockTask('charge').returns('ch_2');
3
env.mockTask('reserveStock').throws(new Error('out of stock'));
4
env.mockTask<string, void>('refund').withFn((chargeId) => {
5
assert.equal(chargeId, 'ch_2');
6
});
7
8
const result = await env.executeWorkflow(orderWorkflow, { orderId: '2', amount: 500 });
9
10
assert.deepEqual(result, { status: 'refunded' });
11
assert.equal(env.getTaskCallCount('refund'), 1);
12
assert.equal(env.getTaskCallCount('sendReceipt'), 0);
13
});

Tasks are not retried in the test environment: a mock that throws fails the call at once, and the workflow's catch sees the mock's own error.


Controlling Time

ctx.sleep() waits on the test clock. Start the workflow, move the clock with env.advanceTime(ms), then await the result:

1
it('charges, reserves, and sends a receipt an hour later', async () => {
2
env.mockTask('charge').returns('ch_1');
3
env.mockTask('reserveStock').returns('res_1');
4
env.mockTask('sendReceipt').returns(undefined);
5
6
const run = env.executeWorkflow(orderWorkflow, { orderId: '1', amount: 500 });
7
await env.advanceTime(60 * 60 * 1000); // the hour passes at once
8
9
assert.deepEqual(await run, { status: 'completed', chargeId: 'ch_1' });
10
env.assertTaskCalled('charge', 1);
11
env.assertTaskCalledWith('charge', { orderId: '1', amount: 500 });
12
});

ctx.time reads the same clock. getCurrentTime(), setCurrentTime(date) and advanceTimeTo(date) read and set it directly.


Asserting on Calls

MethodDescription
env.assertTaskCalled(name, count?)Throws unless the task was called (exactly count times, if given)
env.assertTaskCalledWith(name, input)Throws unless some call had this input
env.getTaskCallCount(name)The number of calls
env.getMockTask(name)An inspector: callCount, calls, wasCalled, wasCalledWith(input)
1
it('records each call', async () => {
2
env.mockTask('charge').returns('ch_3');
3
env.mockTask('reserveStock').throws(new Error('out of stock'));
4
env.mockTask('refund').returns(undefined);
5
6
await env.executeWorkflow(orderWorkflow, { orderId: '3', amount: 700 });
7
8
const reserve = env.getMockTask('reserveStock');
9
assert.equal(reserve.callCount, 1);
10
assert.ok(reserve.wasCalledWith('3'));
11
});

What the Test Environment Covers

The environment runs the workflow against a stand-in for WorkflowContext that implements:

  • executeTask, through the mocks
  • sleep and ctx.time, on the test clock
  • waitForEvent, registerQueryHandler, setState, workflowId(), taskQueue()
  • getState, which returns a Promise here, unlike the real context
  • ctx.random.uuid() and ctx.random.random()

It does not implement execute, sleepWithId, waitForEventWithTimeout, startChildWorkflow, createSession, ctx.random.choose/randomRange/shuffle, or the other metadata methods, and restartFresh throws. It has no way for a test to send an event, and running child workflows needs a registration step the environment does not expose. Test workflows that use these against a real engine, or move the logic they guard into functions you can test directly.

The environment also does not replay, so it does not check determinism. Since tasks never suspend in it, a missing isWorkflowSuspension() check is not caught either: review catch blocks in workflows with that in mind.


Testing Task Logic

A task's TaskContext comes from the worker, so test the logic in a task rather than the task function itself: keep it in plain functions that take ordinary arguments, and call those from the task and from your tests.


Next Steps