Skip to content

Commit

Permalink
Support use of t.end as callback.
Browse files Browse the repository at this point in the history
* Binds all Test.prototype methods to current test.
* Checks for truthy error as first argument to Test.prototype.end.

Closes #180.
  • Loading branch information
timoxley committed Nov 10, 2015
1 parent 4399e7b commit baa2320
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ function Test(title, fn) {
if (this.title === 'callee$0$0') {
this.title = '[anonymous]';
}

Object.keys(Test.prototype).forEach(function (key) {
this[key] = this[key].bind(this);
}, this);
}

module.exports = Test;
Expand Down Expand Up @@ -134,7 +138,11 @@ Test.prototype.run = function () {
}.bind(this));
};

Test.prototype.end = function () {
Test.prototype.end = function (err) {
if (arguments.length >= 1 && err) {
this.ifError(err);
}

if (this.endCalled) {
throw new Error('.end() called more than once');
}
Expand Down
13 changes: 13 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,19 @@ test(async t => {

*You don't have to manually call `t.end()`.*

### Callback support

AVA supports using `t.end` as the final callback when using node-style
error-first callback APIs. AVA will consider any truthy value passed as
the first argument to `t.end` to be an error.

```js
test(t => {
// t.end automatically checks for error as first argument
fs.readFile('data.txt', t.end);
});
```


## API

Expand Down
18 changes: 18 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,24 @@ test('handle non-assertion errors', function (t) {
});
});

test('end can be used as callback without maintaining thisArg', function (t) {
ava(function (a) {
setTimeout(a.end);
}).run().then(function (a) {
t.false(a.assertError);
t.end();
});
});

test('end can be used as callback with error', function (t) {
ava(function (a) {
a.end(new Error('failed'));
}).run().catch(function (err) {
t.true(err instanceof Error);
t.end();
});
});

test('handle non-assertion errors even when planned', function (t) {
ava(function (a) {
a.plan(1);
Expand Down

0 comments on commit baa2320

Please sign in to comment.