Skip to content

Commit 1164c47

Browse files
authoredFeb 11, 2023
fix(expect): check for no 'throw' type in toHaveReturned (#2850)
* 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
1 parent 445c7b3 commit 1164c47

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed
 

‎packages/expect/src/jest-expect.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -549,7 +549,7 @@ export const JestChaiExpect: ChaiPlugin = (chai, utils) => {
549549
def(['toHaveReturned', 'toReturn'], function () {
550550
const spy = getSpy(this)
551551
const spyName = spy.getMockName()
552-
const calledAndNotThrew = spy.mock.calls.length > 0 && !spy.mock.results.some(({ type }) => type === 'throw')
552+
const calledAndNotThrew = spy.mock.calls.length > 0 && spy.mock.results.some(({ type }) => type !== 'throw')
553553
this.assert(
554554
calledAndNotThrew,
555555
`expected "${spyName}" to be successfully called at least once`,

‎test/core/test/fn.test.ts

+9-5
Original file line numberDiff line numberDiff line change
@@ -60,29 +60,33 @@ describe('mock', () => {
6060
let i = 0
6161

6262
const fn = vitest.fn(() => {
63-
if (i === 1) {
63+
if (i === 0) {
6464
++i
6565
throw new Error('error')
6666
}
6767

6868
return String(++i)
6969
})
7070

71-
fn()
7271
try {
7372
fn()
7473
}
7574
catch {}
75+
expect(fn).not.toHaveReturned()
76+
77+
fn()
78+
expect(fn).toHaveReturned()
79+
7680
fn()
7781

7882
try {
79-
expect(fn).toHaveNthReturnedWith(2, '2')
80-
assert.fail('expect should throw, since 2nd call is thrown')
83+
expect(fn).toHaveNthReturnedWith(1, '1')
84+
assert.fail('expect should throw, since 1st call is thrown')
8185
}
8286
catch {}
8387

8488
// not throws
85-
expect(fn).not.toHaveNthReturnedWith(2, '2')
89+
expect(fn).not.toHaveNthReturnedWith(1, '1')
8690

8791
expect(fn).toHaveReturnedTimes(2)
8892
expect(fn).toHaveNthReturnedWith(3, '3')

0 commit comments

Comments
 (0)
Please sign in to comment.