I’m writing a medium test for a workflow and would like to test that the sleep logic behaves as expected. My first attempt was to do something like this:
test('should sleep for 1 day after a failed attempt', async () => {
const startTime = await temporal.env.currentTimeMs();
let elapsedTime = 0;
myMockActivity
.mockReturnValueOnce(false)
.mockImplementationOnce(async () => {
elapsedTime = (await temporal.env.currentTimeMs()) - startTime;
return true;
});
await run('123', temporal);
// 1 day in milliseconds is 86400000
expect(elapsedTime).toBe(86400000);
});
However, this obviously doesn’t work since the elapsed time will rarely ever be exactly 86400000 milliseconds. I could change it so that it checks that the value is within ±500 ms, but that seems kind of hacky.
I asked the Temporal Docs AI and it gave me another suggestion: run the workflow without automatic time skipping, advance time by 23h59m59s
, verify that the next activity hasn’t been called, then advance it by 1 or 2 seconds and check that the activity has been called. However, this also seems a bit suboptimal.
Is there a better way to approach the problem of testing time logic? Obviously I trust that the Workflow will sleep for whatever interval I give it – I’m not trying to test the Workflow.sleep()
function itself – but if a workflow has a more complex system of sleep logic it would be nice to verify that everything followed the expected schedule.