Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reports returned values on received function not throw when expect .toThrow() #15541

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions e2e/__tests__/toThrowErrorMatchingSnapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,24 @@ test("throws the error if tested function didn't throw error", () => {
writeFiles(TESTS_DIR, {[filename]: template()});
const {stderr, exitCode} = runJest(DIR, ['-w=1', '--ci=false', filename]);
expect(stderr).toMatch('Received function did not throw');
expect(stderr).toMatch('Returned: undefined');
expect(exitCode).toBe(1);
}
});

test("reports stringified returned value if tested function didn't throw error", () => {
const filename = 'throws-if-tested-function-did-not-throw.test.js';
const template =
makeTemplate(`test('throws the error if tested function did not throw error', () => {
expect(() => { return { foo: 1, bar: { baz: "2", } };}).toThrowErrorMatchingSnapshot();
});
`);

{
writeFiles(TESTS_DIR, {[filename]: template()});
const {stderr, exitCode} = runJest(DIR, ['-w=1', '--ci=false', filename]);
expect(stderr).toMatch('Received function did not throw');
expect(stderr).toMatch('Returned: {"bar": {"baz": "2"}, "foo": 1}');
expect(exitCode).toBe(1);
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ exports[`toThrow error class did not throw at all 1`] = `
Expected constructor: <g>Err</>

Received function did not throw
Returned: undefined
`;

exports[`toThrow error class threw, but class did not match (error) 1`] = `
Expand Down Expand Up @@ -230,6 +231,7 @@ exports[`toThrow regexp did not throw at all 1`] = `
Expected pattern: <g>/apple/</>

Received function did not throw
Returned: undefined
`;

exports[`toThrow regexp threw, but message did not match (error) 1`] = `
Expand Down Expand Up @@ -271,7 +273,8 @@ exports[`toThrow substring did not throw at all 1`] = `

Expected substring: <g>"apple"</>

Received function did not throw
Received function did not throw
Returned: undefined
`;

exports[`toThrow substring threw, but message did not match (error) 1`] = `
Expand Down
12 changes: 12 additions & 0 deletions packages/expect/src/__tests__/toThrowMatchers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@
).toThrowErrorMatchingSnapshot();
});

test('did not throw with a promise', async () => {
await jestExpect(Promise.resolve('banana')).resolves.not.toThrow('apple')

Check failure on line 54 in packages/expect/src/__tests__/toThrowMatchers.test.ts

View workflow job for this annotation

GitHub Actions / Lint

Insert `;`
});

test('threw, but message did not match (error)', () => {
expect(() => {
jestExpect(() => {
Expand Down Expand Up @@ -108,6 +112,10 @@
).toThrowErrorMatchingSnapshot();
});

test('did not throw at all with a promise', async () => {
await jestExpect(Promise.resolve('banana')).resolves.not.toThrow(/apple/)

Check failure on line 116 in packages/expect/src/__tests__/toThrowMatchers.test.ts

View workflow job for this annotation

GitHub Actions / Lint

Insert `;`
});

test('threw, but message did not match (error)', () => {
expect(() => {
jestExpect(() => {
Expand Down Expand Up @@ -187,6 +195,10 @@
).toThrowErrorMatchingSnapshot();
});

test('did not throw at all with a promise', async () => {
await jestExpect(Promise.resolve()).resolves.not.toThrow(Err)

Check failure on line 199 in packages/expect/src/__tests__/toThrowMatchers.test.ts

View workflow job for this annotation

GitHub Actions / Lint

Insert `;`
});

test('threw, but class did not match (error)', () => {
expect(() => {
jestExpect(() => {
Expand Down
104 changes: 91 additions & 13 deletions packages/expect/src/toThrowMatchers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
printExpected,
printReceived,
printWithType,
stringify,
} from 'jest-matcher-utils';
import {formatStackTrace, separateMessageFromStack} from 'jest-message-util';
import {
Expand Down Expand Up @@ -82,13 +83,14 @@
};

let thrown = null;
let returnedValueOnNotThrow;

if (fromPromise && isError(received)) {
thrown = getThrown(received);
} else {
if (typeof received === 'function') {
try {
received();
returnedValueOnNotThrow = received();
} catch (error) {
thrown = getThrown(error);
}
Expand All @@ -107,20 +109,61 @@
}

if (expected === undefined) {
return toThrow(matcherName, options, thrown);
return toThrow(
matcherName,
options,
thrown,
received,
returnedValueOnNotThrow,
);
} else if (typeof expected === 'function') {
return toThrowExpectedClass(matcherName, options, thrown, expected);
return toThrowExpectedClass(
matcherName,
options,
thrown,
expected,
received,
returnedValueOnNotThrow,
);
} else if (typeof expected === 'string') {
return toThrowExpectedString(matcherName, options, thrown, expected);
return toThrowExpectedString(
matcherName,
options,
thrown,
expected,
received,
returnedValueOnNotThrow,
);
} else if (expected !== null && typeof expected.test === 'function') {
return toThrowExpectedRegExp(matcherName, options, thrown, expected);
return toThrowExpectedRegExp(
matcherName,
options,
thrown,
expected,
received,
returnedValueOnNotThrow,
);
} else if (
expected !== null &&
typeof expected.asymmetricMatch === 'function'
) {
return toThrowExpectedAsymmetric(matcherName, options, thrown, expected);
return toThrowExpectedAsymmetric(
matcherName,
options,
thrown,
expected,
received,
returnedValueOnNotThrow,
);
} else if (expected !== null && typeof expected === 'object') {
return toThrowExpectedObject(matcherName, options, thrown, expected);
return toThrowExpectedObject(
matcherName,
options,
thrown,
expected,
received,
returnedValueOnNotThrow,
);
} else {
throw new Error(
matcherErrorMessage(
Expand All @@ -143,6 +186,8 @@
options: MatcherHintOptions,
thrown: Thrown | null,
expected: RegExp,
received: unknown,
returnedValueOnNotThrow: unknown,
): SyncExpectationResult => {
const pass = thrown !== null && expected.test(thrown.message);

Expand All @@ -166,7 +211,11 @@
'\n\n' +
formatExpected('Expected pattern: ', expected) +
(thrown === null
? `\n${DID_NOT_THROW}`
? `\n${DID_NOT_THROW}${
typeof received === 'function'
? `\nReturned: ${stringify(returnedValueOnNotThrow)}`
: ''

Check warning on line 217 in packages/expect/src/toThrowMatchers.ts

View check run for this annotation

Codecov / codecov/patch

packages/expect/src/toThrowMatchers.ts#L217

Added line #L217 was not covered by tests
}`
: thrown.hasMessage
? formatReceived('Received message: ', thrown, 'message') +
formatStack(thrown)
Expand All @@ -184,6 +233,8 @@
options: MatcherHintOptions,
thrown: Thrown | null,
expected: AsymmetricMatcher,
received: unknown,
returnedValueOnNotThrow: unknown,
): SyncExpectationResult => {
const pass = thrown !== null && expected.asymmetricMatch(thrown.value);

Expand All @@ -206,7 +257,11 @@
formatExpected('Expected asymmetric matcher: ', expected) +
'\n' +
(thrown === null
? DID_NOT_THROW
? `${DID_NOT_THROW}${

Check warning on line 260 in packages/expect/src/toThrowMatchers.ts

View check run for this annotation

Codecov / codecov/patch

packages/expect/src/toThrowMatchers.ts#L260

Added line #L260 was not covered by tests
typeof received === 'function'
? `\nReturned: ${stringify(returnedValueOnNotThrow)}`
: ''

Check warning on line 263 in packages/expect/src/toThrowMatchers.ts

View check run for this annotation

Codecov / codecov/patch

packages/expect/src/toThrowMatchers.ts#L262-L263

Added lines #L262 - L263 were not covered by tests
}`
: thrown.hasMessage
? formatReceived('Received name: ', thrown, 'name') +
formatReceived('Received message: ', thrown, 'message') +
Expand All @@ -221,6 +276,8 @@
options: MatcherHintOptions,
thrown: Thrown | null,
expected: Error,
received: unknown,
returnedValueOnNotThrow: unknown,
): SyncExpectationResult => {
const expectedMessageAndCause = createMessageAndCause(expected);
const thrownMessageAndCause =
Expand Down Expand Up @@ -260,7 +317,11 @@
expectedMessageAndCause,
) +
'\n' +
DID_NOT_THROW
`${DID_NOT_THROW}${
typeof received === 'function'
? `\nReturned: ${stringify(returnedValueOnNotThrow)}`
: ''

Check warning on line 323 in packages/expect/src/toThrowMatchers.ts

View check run for this annotation

Codecov / codecov/patch

packages/expect/src/toThrowMatchers.ts#L322-L323

Added lines #L322 - L323 were not covered by tests
}`
: thrown.hasMessage
? // eslint-disable-next-line prefer-template
printDiffOrStringify(
Expand All @@ -285,6 +346,8 @@
options: MatcherHintOptions,
thrown: Thrown | null,
expected: Function,
received: unknown,
returnedValueOnNotThrow: unknown,
): SyncExpectationResult => {
const pass = thrown !== null && thrown.value instanceof expected;

Expand Down Expand Up @@ -315,7 +378,11 @@
'\n\n' +
printExpectedConstructorName('Expected constructor', expected) +
(thrown === null
? `\n${DID_NOT_THROW}`
? `\n${DID_NOT_THROW}${
typeof received === 'function'
? `\nReturned: ${stringify(returnedValueOnNotThrow)}`
: ''

Check warning on line 384 in packages/expect/src/toThrowMatchers.ts

View check run for this annotation

Codecov / codecov/patch

packages/expect/src/toThrowMatchers.ts#L384

Added line #L384 was not covered by tests
}`
: `${
thrown.value != null &&
typeof thrown.value.constructor === 'function'
Expand All @@ -339,6 +406,8 @@
options: MatcherHintOptions,
thrown: Thrown | null,
expected: string,
received: unknown,
returnedValueOnNotThrow: unknown,
): SyncExpectationResult => {
const pass = thrown !== null && thrown.message.includes(expected);

Expand All @@ -362,7 +431,11 @@
'\n\n' +
formatExpected('Expected substring: ', expected) +
(thrown === null
? `\n${DID_NOT_THROW}`
? `\n${DID_NOT_THROW} ${
typeof received === 'function'
? `\nReturned: ${stringify(returnedValueOnNotThrow)}`
: ''

Check warning on line 437 in packages/expect/src/toThrowMatchers.ts

View check run for this annotation

Codecov / codecov/patch

packages/expect/src/toThrowMatchers.ts#L437

Added line #L437 was not covered by tests
}`
: thrown.hasMessage
? formatReceived('Received message: ', thrown, 'message') +
formatStack(thrown)
Expand All @@ -375,6 +448,8 @@
matcherName: string,
options: MatcherHintOptions,
thrown: Thrown | null,
received: unknown,
returnedValueOnNotThrow: unknown,
): SyncExpectationResult => {
const pass = thrown !== null;

Expand All @@ -392,7 +467,10 @@
// eslint-disable-next-line prefer-template
matcherHint(matcherName, undefined, '', options) +
'\n\n' +
DID_NOT_THROW;
DID_NOT_THROW +
(typeof received === 'function'
? `\nReturned: ${stringify(returnedValueOnNotThrow)}`

Check warning on line 472 in packages/expect/src/toThrowMatchers.ts

View check run for this annotation

Codecov / codecov/patch

packages/expect/src/toThrowMatchers.ts#L472

Added line #L472 was not covered by tests
: '');

return {message, pass};
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ exports[`other error toThrowErrorMatchingSnapshot Received function did not thro
<d>expect(</><r>received</><d>).</>toThrowErrorMatchingSnapshot<d>()</>

Received function did not throw
Returned: undefined
`;

exports[`pass false toMatchInlineSnapshot with properties equals false with snapshot 1`] = `
Expand Down
9 changes: 7 additions & 2 deletions packages/jest-snapshot/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -509,12 +509,13 @@
}

let error;
let returnedValueOnNotThrow;

if (fromPromise) {
error = received;
} else {
try {
received();
returnedValueOnNotThrow = received();
} catch (receivedError) {
error = receivedError;
}
Expand All @@ -523,7 +524,11 @@
if (error === undefined) {
// Because the received value is a function, this is not a matcher error.
throw new Error(
`${matcherHintFromConfig(config, false)}\n\n${DID_NOT_THROW}`,
`${matcherHintFromConfig(config, false)}\n\n${DID_NOT_THROW}${
typeof received === 'function'
? `\nReturned: ${stringify(returnedValueOnNotThrow)}`
: ''

Check warning on line 530 in packages/jest-snapshot/src/index.ts

View check run for this annotation

Codecov / codecov/patch

packages/jest-snapshot/src/index.ts#L530

Added line #L530 was not covered by tests
}`,
);
}

Expand Down
Loading