Skip to content

Commit

Permalink
fix(expect): improve the error message when nothing is thrown when te…
Browse files Browse the repository at this point in the history
…sting `toThrow` (#3979)
  • Loading branch information
Dunqing authored Sep 18, 2023
1 parent 8c3152f commit 725a014
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
10 changes: 10 additions & 0 deletions packages/expect/src/jest-expect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -512,12 +512,22 @@ export const JestChaiExpect: ChaiPlugin = (chai, utils) => {
}
}
else {
let isThrow = false
try {
obj()
}
catch (err) {
isThrow = true
thrown = err
}

if (!isThrow && !isNot) {
const message = utils.flag(this, 'message') || 'expected function to throw an error, but it didn\'t'
const error = {
showDiff: false,
}
throw new AssertionError(message, error, utils.flag(this, 'ssfi'))
}
}

if (typeof expected === 'function') {
Expand Down
16 changes: 16 additions & 0 deletions test/core/test/jest-expect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,22 @@ describe('jest-expect', () => {
},
])
})

describe('toThrow', () => {
it('error wasn\'t thrown', () => {
expect(() => {
expect(() => {
}).toThrow(Error)
}).toThrowErrorMatchingInlineSnapshot('"expected function to throw an error, but it didn\'t"')
})

it('async wasn\'t awaited', () => {
expect(() => {
expect(async () => {
}).toThrow(Error)
}).toThrowErrorMatchingInlineSnapshot('"expected function to throw an error, but it didn\'t"')
})
})
})

describe('.toStrictEqual()', () => {
Expand Down

0 comments on commit 725a014

Please sign in to comment.