From 1164c4785429bc67e0eb082c0b98a32195427ac0 Mon Sep 17 00:00:00 2001 From: Trivikram Kamat <16024985+trivikr@users.noreply.github.com> Date: Sat, 11 Feb 2023 04:34:06 -0800 Subject: [PATCH] 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 --- packages/expect/src/jest-expect.ts | 2 +- test/core/test/fn.test.ts | 14 +++++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/packages/expect/src/jest-expect.ts b/packages/expect/src/jest-expect.ts index 30f135865574..3528aa157f3a 100644 --- a/packages/expect/src/jest-expect.ts +++ b/packages/expect/src/jest-expect.ts @@ -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`, diff --git a/test/core/test/fn.test.ts b/test/core/test/fn.test.ts index 8258c602cdf7..433312de084e 100644 --- a/test/core/test/fn.test.ts +++ b/test/core/test/fn.test.ts @@ -60,7 +60,7 @@ describe('mock', () => { let i = 0 const fn = vitest.fn(() => { - if (i === 1) { + if (i === 0) { ++i throw new Error('error') } @@ -68,21 +68,25 @@ describe('mock', () => { 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')