From 9b81e2bd56a49d6ef2c57ba73089ead09d6e6e19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Fre=C3=9Fdorf?= Date: Wed, 25 Aug 2021 20:38:34 +0200 Subject: [PATCH] Keep original function implementation when not matched --- src/when.js | 5 +++-- src/when.test.js | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/when.js b/src/when.js index 58435e9..e75a090 100644 --- a/src/when.js +++ b/src/when.js @@ -96,8 +96,9 @@ class WhenMock { return mockImplementation(...args) } } - - return defaultImplementation ? defaultImplementation(...args) : undefined + return defaultImplementation ? defaultImplementation(...args) + : (typeof fn.__whenMock__._origMock === 'function' + ? fn.__whenMock__._origMock(...args) : undefined) }) return { diff --git a/src/when.test.js b/src/when.test.js index 64b99ae..cf161c7 100644 --- a/src/when.test.js +++ b/src/when.test.js @@ -835,5 +835,30 @@ describe('When', () => { const returnValue = theInstance.theMethod(1) expect(returnValue).toBe('mock') }) + + it('keeps default function implementation when not matched', () => { + class TheClass { + fn () { + return 'real' + } + } + const instance = new TheClass() + const spy = jest.spyOn(instance, 'fn') + when(spy) + .calledWith(1) + .mockReturnValue('mock') + expect(instance.fn(2)).toBe('real') + }) + + it('keeps default mock implementation when not matched', () => { + const fn = jest.fn(() => { + return 'real' + }) + when(fn) + .calledWith(1) + .mockReturnValue('mock') + expect(fn(1)).toBe('mock') + expect(fn(2)).toBe('real') + }) }) })