Skip to content

Commit

Permalink
Support use of t.end as callback, closes #180
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.
  • Loading branch information
timoxley authored and vdemedes committed Nov 16, 2015
1 parent 6b62884 commit 403a28c
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
16 changes: 15 additions & 1 deletion lib/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,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 @@ -147,7 +151,17 @@ Test.prototype.run = function () {
}.bind(this));
};

Test.prototype.end = function () {
Test.prototype.end = function (err) {
if (err) {
this.assertError = new assert.AssertionError({
actual: err,
message: 'Callback called with an error → ' + err,
operator: 'callback'
});

return this.exit();
}

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 @@ -339,6 +339,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 @@ -140,6 +140,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 403a28c

Please sign in to comment.