Skip to content

Commit 725a014

Browse files
authored
fix(expect): improve the error message when nothing is thrown when testing toThrow (#3979)
1 parent 8c3152f commit 725a014

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

packages/expect/src/jest-expect.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,12 +512,22 @@ export const JestChaiExpect: ChaiPlugin = (chai, utils) => {
512512
}
513513
}
514514
else {
515+
let isThrow = false
515516
try {
516517
obj()
517518
}
518519
catch (err) {
520+
isThrow = true
519521
thrown = err
520522
}
523+
524+
if (!isThrow && !isNot) {
525+
const message = utils.flag(this, 'message') || 'expected function to throw an error, but it didn\'t'
526+
const error = {
527+
showDiff: false,
528+
}
529+
throw new AssertionError(message, error, utils.flag(this, 'ssfi'))
530+
}
521531
}
522532

523533
if (typeof expected === 'function') {

test/core/test/jest-expect.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,22 @@ describe('jest-expect', () => {
368368
},
369369
])
370370
})
371+
372+
describe('toThrow', () => {
373+
it('error wasn\'t thrown', () => {
374+
expect(() => {
375+
expect(() => {
376+
}).toThrow(Error)
377+
}).toThrowErrorMatchingInlineSnapshot('"expected function to throw an error, but it didn\'t"')
378+
})
379+
380+
it('async wasn\'t awaited', () => {
381+
expect(() => {
382+
expect(async () => {
383+
}).toThrow(Error)
384+
}).toThrowErrorMatchingInlineSnapshot('"expected function to throw an error, but it didn\'t"')
385+
})
386+
})
371387
})
372388

373389
describe('.toStrictEqual()', () => {

0 commit comments

Comments
 (0)