0

The problem

The popular ava package features a simple and powerful testing framework for javascript:

import test from 'ava';

test('single step', t => {
    t.is('bar', 'bar');
    t.end();
});

Testing is dead simple for synchronous code. However, I am not sure how to write tests with multiple, consecutive, dependent steps.

For example, I would like to test a REST API. I would like to create a resource using POST, make sure it exists with GET call, and delete it with DELETE.

Needless to say, the order matters: the POST call must be finished before the GET call can start, and sometimes we even want a sleep time between steps.

What have I tried

  • Tried a series of setTimeouts where where the callback of each call is the next test step. It is fairly unreadable.

My question

What's the right way to write a test with multiple consecutive steps with ava?

These steps are asynchronous and consecutive

Adam Matan
  • 128,757
  • 147
  • 397
  • 562

2 Answers2

2

If you're looking to have all these steps in a single test, make sure you can get promises out of your request library. Then use async / await.

Mark Wubben
  • 3,329
  • 1
  • 19
  • 16
0

You can mix slow functions and logic into complex scenarios if you run your code via sequential executor nsynjs. You just need to write your code as if it was synchronous, and put it into function:

function process() {
    var data = jQueryGetJSON(nsynjsCtx, "data/index.json").data; // ajax call to get some data
    for(var i in data) { // data is ready at this point
        var resp = jQueryGetJSON(nsynjsCtx, "data/"+data[i]).data;  // another ajax call
        // ... resp is ready here, do processing of resp...
        nsynWait(nsynjsCtx,100); // wait 100ms
    }
    return someResult;
}

Then you run that function via nsynjs:

nsynjs.run(process,this,function (someResult) {
    console.log('done');
    // put t.end() inside this callback
});

See more examples here: https://github.com/amaksr/nsynjs/tree/master/examples

amaksr
  • 7,555
  • 2
  • 16
  • 17