task.spec.js
1 import { Task } from './lib.js' 2 3 /** 4 * @type {import('entail').Suite} 5 */ 6 export const testTask = { 7 'test sync': (assert) => 8 Task.spawn(function* () { 9 /** 10 * @template T 11 * @param {T} x 12 */ 13 function* ok(x) { 14 return x 15 } 16 17 const invocation = Task.perform(ok(4)) 18 const output = yield* invocation 19 assert.equal(output, 4) 20 }), 21 'task sleep can be aborted': async (assert) => { 22 const task = Task.perform(Task.sleep(10)) 23 24 task.abort('cancel') 25 26 const result = await task.result() 27 assert.deepEqual(result.error?.reason, 'cancel') 28 assert.deepEqual(result.error?.name, 'AbortError') 29 }, 30 31 'sleep awake': async (assert) => { 32 const task = Task.perform(Task.sleep(10)) 33 const result = await task.result() 34 assert.deepEqual(result, { ok: undefined }) 35 }, 36 37 'task cancels joined task': async (assert) => { 38 let done = false 39 function* worker() { 40 yield* Task.sleep(10) 41 done = true 42 } 43 44 function* main() { 45 return yield* Task.spawn(worker) 46 } 47 48 const task = Task.perform(main()) 49 task.abort('cancel') 50 const result = await task.result() 51 assert.deepEqual(result.error?.reason, 'cancel') 52 53 await new Promise((resolve) => setTimeout(resolve, 20)) 54 55 assert.deepEqual(done, false) 56 }, 57 58 'test wait': async (assert) => { 59 const task = Task.spawn(function* () { 60 const value = yield* Task.wait(Promise.resolve(4)) 61 return value 62 }) 63 64 assert.deepEqual(await task.result(), { ok: 4 }) 65 }, 66 }