Skip to content

Commit

Permalink
fix(expect): check for no 'throw' type in toHaveReturned (#2850)
Browse files Browse the repository at this point in the history
* test: not.toHaveReturned when mock fn throws

* test: update toHaveNthReturnedWith test in fn.throws

* fix(expect): check for successful return in toHaveReturned

* test: update toHaveNthReturnedWith with 1st call which throws
  • Loading branch information
trivikr authored Feb 11, 2023
1 parent 445c7b3 commit 1164c47
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
2 changes: 1 addition & 1 deletion packages/expect/src/jest-expect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,7 @@ export const JestChaiExpect: ChaiPlugin = (chai, utils) => {
def(['toHaveReturned', 'toReturn'], function () {
const spy = getSpy(this)
const spyName = spy.getMockName()
const calledAndNotThrew = spy.mock.calls.length > 0 && !spy.mock.results.some(({ type }) => type === 'throw')
const calledAndNotThrew = spy.mock.calls.length > 0 && spy.mock.results.some(({ type }) => type !== 'throw')
this.assert(
calledAndNotThrew,
`expected "${spyName}" to be successfully called at least once`,
Expand Down
14 changes: 9 additions & 5 deletions test/core/test/fn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,29 +60,33 @@ describe('mock', () => {
let i = 0

const fn = vitest.fn(() => {
if (i === 1) {
if (i === 0) {
++i
throw new Error('error')
}

return String(++i)
})

fn()
try {
fn()
}
catch {}
expect(fn).not.toHaveReturned()

fn()
expect(fn).toHaveReturned()

fn()

try {
expect(fn).toHaveNthReturnedWith(2, '2')
assert.fail('expect should throw, since 2nd call is thrown')
expect(fn).toHaveNthReturnedWith(1, '1')
assert.fail('expect should throw, since 1st call is thrown')
}
catch {}

// not throws
expect(fn).not.toHaveNthReturnedWith(2, '2')
expect(fn).not.toHaveNthReturnedWith(1, '1')

expect(fn).toHaveReturnedTimes(2)
expect(fn).toHaveNthReturnedWith(3, '3')
Expand Down

0 comments on commit 1164c47

Please sign in to comment.