Skip to content

Commit 85bfb22

Browse files
committed
Merge pull request #91 from sindresorhus/throws-fixes
Fix t.throws() behavior to avoid false-positives and regex suport
2 parents c628c6d + 593a6f9 commit 85bfb22

File tree

2 files changed

+35
-7
lines changed

2 files changed

+35
-7
lines changed

lib/assert.js

+8-6
Original file line numberDiff line numberDiff line change
@@ -70,19 +70,21 @@ x.notSame = function (val, expected, msg) {
7070

7171
x.throws = function (fn, err, msg) {
7272
if (fn && fn.then) {
73-
err = err || Error;
73+
var isFailed = false;
7474

7575
return fn
76-
.catch(err, function (err) {
76+
.catch(function (err) {
77+
isFailed = true;
78+
7779
return err;
7880
})
79-
.then(function (value) {
80-
if (value instanceof err) {
81-
return;
81+
.then(function (fnErr) {
82+
if (!isFailed) {
83+
x.throws(function () {}, err, msg);
8284
}
8385

8486
x.throws(function () {
85-
throw value;
87+
throw fnErr;
8688
}, err, msg);
8789
});
8890
}

test/test.js

+27-1
Original file line numberDiff line numberDiff line change
@@ -204,8 +204,33 @@ test('handle throws with resolved promise', function (t) {
204204
var promise = Promise.resolve();
205205
a.throws(promise);
206206
}).run().catch(function (err) {
207+
t.true(err);
207208
t.is(err.name, 'AssertionError');
209+
t.end();
210+
});
211+
});
212+
213+
test('handle throws with regex', function (t) {
214+
ava(function (a) {
215+
a.plan(1);
216+
217+
var promise = Promise.reject(new Error('abc'));
218+
a.throws(promise, /abc/);
219+
}).run().then(function (a) {
220+
t.false(a.assertionError);
221+
t.end();
222+
});
223+
});
224+
225+
test('handle throws with false-positive promise', function (t) {
226+
ava(function (a) {
227+
a.plan(1);
228+
229+
var promise = Promise.resolve(new Error());
230+
a.throws(promise);
231+
}).run().catch(function (err) {
208232
t.true(err);
233+
t.is(err.name, 'AssertionError');
209234
t.end();
210235
});
211236
});
@@ -218,8 +243,8 @@ test('handle doesNotThrow with error', function (t) {
218243

219244
a.end();
220245
}).run().catch(function (err) {
221-
t.is(err.name, 'AssertionError');
222246
t.true(err);
247+
t.is(err.name, 'AssertionError');
223248
t.end();
224249
});
225250
});
@@ -257,6 +282,7 @@ test('handle doesNotThrow with rejected promise', function (t) {
257282
a.doesNotThrow(promise);
258283
}).run().catch(function (err) {
259284
t.true(err);
285+
t.is(err.name, 'AssertionError');
260286
t.end();
261287
});
262288
});

0 commit comments

Comments
 (0)