Search code examples
javascriptnode.jstestingtddnode.js-tape

What is the purpose of using "plan" vs "end" in substack/tape?


substack's tape testing module allows you to specify the number of assertions ahead of time with the plan method, and then it will automatically call end for you. Why not just put end at the end of a test? What is the difference between using plan, and end?


Solution

  • The first example on the readme shows a situation where plan works but end wouldn't - asynchronous test resolution. In this case, you're not explicitly saying when the tests should all have resolved, you're saying how many should eventually resolve:

    test('timing test', function (t) {
        t.plan(2);
    
        t.equal(typeof Date.now, 'function');
        var start = Date.now();
    
        setTimeout(function () {
            t.equal(Date.now() - start, 100);
        }, 100);
    });
    

    If we were using end, the intuitive way to write this test would be as follows:

    test('timing test', function (t) {
        t.equal(typeof Date.now, 'function');
        var start = Date.now();
    
        setTimeout(function () {
            t.equal(Date.now() - start, 100);
        }, 100);
    
        t.end();
    });
    

    ...but this would end the test before the second assertion has had a chance to run.

    You can extrapolate this further to any kind of situation where asynchronous or dynamic code needs to execute.