Skip to content

Commit

Permalink
Output message when t.throws() fails (#1408)
Browse files Browse the repository at this point in the history
  • Loading branch information
timdeschryver authored and sindresorhus committed Jun 13, 2017
1 parent e456951 commit dfca2d9
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
10 changes: 8 additions & 2 deletions lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ function wrapAssertions(callbacks) {
const fail = callbacks.fail;

const noop = () => {};
const makeNoop = () => noop;
const makeRethrow = reason => () => {
throw reason;
};
Expand Down Expand Up @@ -174,7 +173,14 @@ function wrapAssertions(callbacks) {
if (promise) {
// Record stack before it gets lost in the promise chain.
const stack = getStack();
const intermediate = promise.then(makeNoop, makeRethrow).then(fn => test(fn, stack));
const intermediate = promise.then(value => {
throw new AssertionError({
assertion: 'throws',
message: 'Expected promise to be rejected, but it was resolved instead',
values: [formatAssertError.formatWithLabel('Resolved with:', value)]
});
}, reason => test(makeRethrow(reason), stack));

pending(this, intermediate);
// Don't reject the returned promise, even if the assertion fails.
return intermediate.catch(noop);
Expand Down
31 changes: 27 additions & 4 deletions test/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,18 @@ const assertions = assert.wrapAssertions({
lastPassed = true;
},

pending() {},
pending(_, promise) {
promise.catch(err => {
lastFailure = err;
});
},

fail(_, error) {
lastFailure = error;
}
});

function failsWith(t, fn, subset) {
lastFailure = null;
fn();
function assertFailure(t, subset) {
if (!lastFailure) {
t.fail('Expected assertion to fail');
return;
Expand Down Expand Up @@ -51,6 +53,19 @@ function failsWith(t, fn, subset) {
}
}

function failsWith(t, fn, subset) {
lastFailure = null;
fn();
assertFailure(t, subset);
}

function eventuallyFailsWith(t, promise, subset) {
lastFailure = null;
return promise.then(() => {
assertFailure(t, subset);
});
}

function fails(t, fn) {
lastFailure = null;
fn();
Expand Down Expand Up @@ -648,6 +663,14 @@ test('.throws() fails if passed a bad value', t => {
t.end();
});

test('promise .throws() fails when promise is resolved', t => {
return eventuallyFailsWith(t, assertions.throws(Promise.resolve('foo')), {
assertion: 'throws',
message: 'Expected promise to be rejected, but it was resolved instead',
values: [{label: 'Resolved with:', formatted: formatValue('foo')}]
});
});

test('.notThrows()', t => {
passes(t, () => {
assertions.notThrows(() => {});
Expand Down

0 comments on commit dfca2d9

Please sign in to comment.