TestSync: A Helper for Testing Intricate Async Logic
TestSync is a little helper library to aid in testing intricate ordering of asynchronous code in Javascript. TypeScript typings are included.
This library is feature complete and new new development is anticipated (though who knows).
You probably want to use this library as a dev dependency:
npm install --save-dev testsyncSometimes you need to build intricate test cases around asynchronous logic to ensure that, given certain ordering of operations of asynchronous code, things still operate correctly. This can be tricky to guarantee in any asynchronous system! This library can help.
It does this by providing "synchronization points" (promises) that can be awaited in your code. Once awaited enough times, the synchronization promises will automatically resolved, and your code will continue.
Imagine you have an asynchronous cache, and you want to validate that given a certain order of operations on that cache, things behave as expected. How might you test that? With testsync, it's easy:
constsync=require('testsync')const[precache,cached]=sync()consturl='http://example.org'constcache=newAsyncCache()asyncfunctionworker1(){constdata=awaitfetchUrl(url)awaitprecacheawaitcache.set(url,data)awaitcached}asyncfunctionworker2(){expect(awaitcache.get(url)).to.be.undefinedawaitprecacheawaitcachedexpect(awaitcache.get(url)).to.be.ok}awaitPromise.all([worker1(),worker2()])The API is very simple. First import the sync function (all of the below will work equivalently):
const{ sync }=require('testsync')constsync=require('testsync')importsyncfrom'testsync'import{sync}from'testsync'The sync method has the signature:
function*sync(awaitCount=2)This is a generator function that returns as many synchronization points as you'd like. They will resolve only when they've been awaited (or .thend) the specified (count, default 2) number of times. The promise will never throw.
To create new promises, use destructuring:
const[beforeUpdate,afterUpdate,afterSave]=sync()const[threeWaySyncPoint]=sync(3)You can create as many synchronization points as you like this way. Afterwards, just await them as normal (from within separate async contexts, obviously), and when the promise is being awaited in the minimum number of places, it will automatically resolve:
const[a,b]awaitPromise.all([newPromise(resolve=>{awaitaawaitbresolve()}),newPromise(resolve=>{awaitaawaitbresolve()})])const[a,b,c]=sync()// equivalent to sync(2)awaitPromise.all([a,a])// resolves, `a` is awaited twiceawaitPromise.all([b])// never resolves, only awaited onceawaitPromise.all([c,c,c])// can be awaited more than `count` timesconst[d,e]=sync(3)awaitPromise.all([d,d])// again never resolves, must be awaited 3 timesawaitPromise.all([e,e,e])// resolvesMIT