Actually you can use jest.spyOn jest.spyOn

If method is called when component created use:

import { mount } from 'enzyme'; 

describe('My component', () => {
  it('should call getData', () => {
    const spy = jest.spyOn(Component.prototype, 'getData');
    mount(<Component />);
    expect(spy).toHaveBeenCalledTimes(1)
  });
})

or if you have it in your DOM and method use bind you can use:

import { shallow } from 'enzyme'; 

describe('My component', () => {
  it('should call getData', () => {
    const wrapper = shallow(<Component />);
    const instance = wrapper.instance()
    const spy = jest.spyOn(instance, 'getData');
    wrapper.find('button').simulate('click')
    expect(spy).toHaveBeenCalledTimes(1)
  });
})
Answer from Denis Rybalka on Stack Overflow
🌐
Jest
jestjs.io › the jest object
The Jest Object · Jest
1 week ago - By default, jest.spyOn also calls the spied method. This is different behavior from most other test libraries.
🌐
Echobind
echobind.com › post › how-to-mock-using-jest-spyon-part-2-3
How to Mock Using Jest.spyOn (Part 2)
October 16, 2019 - test('creates Contract on correct date', () => { const NOW = '2019-05-03T08:00:00.000Z'; const mockDateNow = jest .spyOn(global.Date, 'now') .mockImplementation(() => new Date(NOW).getTime()); const mutation = ` mutation createContract { createContract { startedOn } } `; const response = await ...
🌐
Meticulous
meticulous.ai › blog › how-to-use-jest-spyon
How to use Jest spyOn with React.js and Fetch
This also verifies the country ISO code and percent are as expected, for example US - 4.84% for the US. Similarly, it inspects that there are flag images with expected alt text. Congratulations! Now we have successfully mocked the fetch call with Jest SpyOn and also verified the happy path result.
🌐
Code with Hugo
codewithhugo.com › jest-fn-spyon-stub-mock
Jest .fn() and .spyOn() spy/stub/mock assertion reference · Code with Hugo
November 5, 2019 - So for example with the spyOn(counter) ... assert on that. test('app() with jest.spyOn(counter) .toHaveBeenCalledTimes(1)', () => { // existing test setup/assertion code expect(counter.getCount()).toEqual(1); });...
🌐
DEV Community
dev.to › devin-rosario › complete-guide-to-jestspyon-for-unit-testing-4io6
Complete Guide to Jest.spyOn for Unit Testing - DEV Community
October 16, 2025 - const spy = jest.spyOn(analytics, ... events · Catches over-calling or under-calling. Production example: analytics tracking firing twice per action....
🌐
Sevic
sevic.dev › notes › spies-mocking-jest
Spies and mocking with Jest | Željko Šević | Node.js Developer
August 19, 2021 - jest · .spyOn(calculationService, 'calculate') .mockImplementationOnce((a) => a + 3) .mockImplementationOnce((a) => a + 5); External modules can be mocked similarly to spies. For the following example, let's suppose axios package is already used in one function.
🌐
JavaScript in Plain English
javascript.plainenglish.io › jest-spies-and-mocks-in-explained-via-examples-71229077277f
Jest Spies and Mocks Explained via Examples | by John C. Lokman | JavaScript in Plain English
July 24, 2024 - Testing Jest Spies and Mocks Explained via Examples Make your JavaScript tests deeper, leaner, and faster with these two Jest methods 👁 Spying jest.spyOn( PROTOTYPE_OR_CLASS, METHOD_NAME ) Spying …
Find elsewhere
🌐
Medium
medium.com › @catherineangelr › testing-with-spy-and-mock-in-jest-a-beginners-guide-7a25f87010c2
Testing with Spy, Mock, and Stub in Jest: A Beginner’s Guide | by Catherine Angel | Medium
May 21, 2024 - To create spy, you can use jest.spyOn() with 2 arguments given: the object and the method. Some functionalities that are provided by spy functions are tracking the number of times the funtion has been called, the parameters that is is called with and also the value it returns.
🌐
Jest
jestjs.io › mock functions
Mock Functions · Jest
1 week ago - Constructs the type of a spied class or function (i.e. the return type of jest.spyOn()).
🌐
Position Is Everything
positioniseverything.net › home › jest spyon: all you need to know about this function
Jest Spyon: All You Need To Know About This Function - Position Is Everything
November 12, 2025 - Some key points are: It is a functional app with React that guesses the nationality of a given name by calling an API. Jest spyon has the ability to spy on the method calls and parameters like Jest Mock/fn.
🌐
Medium
medium.com › @eklavya_ › jest-spy-vs-mock-when-to-use-what-60b8720f3ed0
Jest Spy vs Mock — when to use what! | by Gunjan Kalita | Medium
April 25, 2025 - describe('What time is it:', () => { it('Verify that 15 returns afternoon', () => { const mockDate = new Date(2021, 3, 24, 15, 0, 30, 0) // Create a system spy. const spy = jest.spyOn(global, 'Date'); spy.mockImplementationOnce(() => mockDate); ...
🌐
Medium
rrish7g.medium.com › jest-fn-vs-jest-spyon-understanding-the-differences-for-effective-testing-0f5928f7a411
Jest.fn() vs Jest.spyOn(): Understanding the Differences for Effective Testing | by Rrish | Medium
November 27, 2023 - Real Behaviour Testing: For integration tests where the actual implementation contributes to the behaviour under test, jest.spyOn() allows you to verify the integration without stubbing out the code.
🌐
Frontend Masters
frontendmasters.com › courses › testing-practices-principles › using-jest-spyon
Using Jest spyOn - JavaScript Testing Practices and ...
Whether you want to learn professional JavaScript and TypeScript, to back-end courses on Node.js, SQL, and beyond we have courses to bring your skills to the next level!
🌐
Chakshunyu
chakshunyu.com › blog › how-to-spy-on-a-named-import-in-jest
How To Spy On An Exported Function In Jest | A technical blog by Chak Shun Yu
import { functionToMock } from '@module/api'; jest.spyOn(???, 'functionToMock').mockReturnValue({ someObjectProperty: 42 }); I want to spy on the named export, but what should I provide to the jest.spyOn function as the first argument? The API requires an entire module or object as its first ...
🌐
Silvenon
silvenon.com › blog › mocking-with-jest › functions
Mocking with Jest: Spying on Functions and Changing Implementation
May 22, 2022 - We can’t just replace Math.random with a mock function because we want to preserve its functionality, instead we can spy on it using jest.spyOn, which wraps it in a mock function and returns it so we can track it: const MontyPython = require('./monty-python') describe('MontyPython', () => { describe('getTheMeaningOfLife', () => { it('reveals the cold hard truth about life', () => { const montyPython = new MontyPython() const mathRandomSpy = jest.spyOn(Math, 'random') montyPython.getTheMeaningOfLife() expect(mathRandomSpy).toHaveBeenCalled() mathRandomSpy.mockRestore() }) }) }) Here Math.random does its thing, we’re not changing its functionality, we’re only temporarily wrapping it in a mock function in order to make assertions on it.
🌐
DhiWise
dhiwise.com › post › grow-testing-efficiency-with-jest-spyon-for-default-exports
A Deep Dive into Jest spyOn for Default Exports
April 30, 2025 - The spyOn method takes two arguments: the object that contains the method and the string name of the method itself. It returns a Jest mock function that can be used to inspect calls to the function.
🌐
Microsoft Developer Blogs
devblogs.microsoft.com › dev blogs › ise developer blog › jest mocking best practices
Jest Mocking Best Practices - ISE Developer Blog
November 4, 2024 - Then we can use the jest.spyon() function on the PersonFactory so that the class’s getInstance method will be overwritten to return our mocked person object. jest.spyOn(PersonFactory, 'getInstance').mockReturnValue(mockAnnika);
Top answer
1 of 3
120

My simple understanding of these two functions in react/frontend projects is the following:

jest.fn()

  • You want to mock a function and really don't care about the original implementation of that function (it will be overridden by jest.fn())
  • Often you just mock the return value
  • This is very helpful if you want to remove dependencies to the backend (e.g. when calling backend API) or third party libraries in your tests
  • It is also extremely helpful if you want to make real unit tests. You don't care about if certain function that gets called by the unit you test is working properly, because thats not part of it's responsibility.

jest.spyOn()

  • The original implementation of the function is relevant for your test, but:
    • You want to add your own implementation just for a specific scenario and then reset it again via mockRestore() (if you just use a jest.spyOn() without mocking it further it will still call the original function by default)
    • You just want to see if the function was called
    • ...
  • I think this is especially helpful for integration tests, but not only for them!

(Good blog post: https://medium.com/@rickhanlonii/understanding-jest-mocks-f0046c68e53c)

2 of 3
55

To my understanding the only difference is that YOU CAN RESTORE ORIGINAL FUNCTION with jest.spyOn and you can't with jest.fn.

Imagine we have some hook that calls a function when component is rendered, here we can just check the function was called, we do not test that function.

Another case if we want original function to test how it works. And we need both in one test file.

Real method:

myMethod() {
  return 33;
}

With jest.fn()

const myMethod = jest.fn().mockImplementation(() => 25);
const result = myMethod();
expect(result).toBe(25);

In case we want to test now real myMethod, we can't restore it back to normal with jest.fn().

Another thing with spies:

const spy_myMethod = jest.spyOn(component, "myMethod").mockImplementation(() => 25);
const result = myMethod();
expect(result).toBe(25);

And now if we want the original myMethod

spy_myMethod.mockRestore();
const result = myMethod();
expect(result).toBe(33);
🌐
Jest
jestjs.io › es6 class mocks
ES6 Class Mocks · Jest
A simple example: // your jest test file below · import SoundPlayer from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; const playSoundFileMock = jest · .spyOn(SoundPlayer.prototype, 'playSoundFile') .mockImplementation(() => { console.log('mocked function'); }); // comment this line if just want to "spy" it('player consumer plays music', () => { const player = new SoundPlayerConsumer(); player.playSomethingCool(); expect(playSoundFileMock).toHaveBeenCalled(); }); Lets imagine our class SoundPlayer has a getter method foo and a static method brand ·