5

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?

oibe
  • 1,047
  • 1
  • 7
  • 10

1 Answers1

5

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.

Barney
  • 16,181
  • 5
  • 62
  • 76
  • 3
    Can we not put a `t.end()` into the setTimeout() callback? – Paragon Nov 28 '18 at 02:38
  • You could. In hindsight this isn't a very good example — a better demonstration of plan would be something that involved potential race conditions, were a certain number of conditions are expected to resolve, but no single conditional resolution can claim to take responsibility for concluding the test. The asynchronous element is orthogonal. – Barney Nov 28 '18 at 18:37
  • Ah, yes, that makes sense! Thanks Barney. – Paragon Nov 29 '18 at 19:18