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 OverflowJest
jestjs.io › the jest object
The Jest Object · Jest
May 7, 2026 - By default, jest.spyOn also calls the spied method. This is different behavior from most other test libraries.
Videos
26:12
Mocking React Components and Functions using Jest for Beginners ...
05:42
React Testing Library tutorial-Mocking jest with spyOn-Part-13 ...
25:12
Mock vs Spy in Testing with Jest: Which is Better? - YouTube
21:51
JestJS Mocking tutorial for busy developers Part 3: jest.spyOn ...
21:28
Instance, Jest.spyOn, State, Props & toBe vs toEqual | #8 | React ...
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 ...
Top answer 1 of 4
76
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)
});
})
2 of 4
22
There is the spyOn method, that was introduced with v19 some days ago, that does exactly what you are looking for
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 - In the previous example, why would we use a complete mock vs a spy? test('app() with mock counter .toHaveBeenCalledTimes(1)', () => { const mockCounter = { increment: jest.fn() }; app(mockCounter); expect(mockCounter.increment).toHaveBeenCalledTimes(1); }); test('app() with jest.spyOn(counter) .toHaveBeenCalledTimes(1)', () => { const incrementSpy = jest.spyOn(counter, 'increment'); app(counter); expect(incrementSpy).toHaveBeenCalledTimes(1); });
Jest
jestjs.io › mock functions
Mock Functions · Jest
May 7, 2026 - Constructs the type of a spied class or function (i.e. the return type of jest.spyOn()).
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!
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.
Meticulous
meticulous.ai › blog › mocking-a-javascript-class-with-jest-two-ways-to-make-it-easier
Mocking a JavaScript Class with Jest, Two Ways to Make it Easier
Using jest spyOn to mock a specific method of an ES6 class is like performing a surgical operation. Using it you can target one or more specific methods called in the test’s context. Below is an example code of the ES6 class mock using Jest spyOn to mock the ExchangeRateClient class' ``getLatestExchangeRate` method only...
Jest
jestjs.io › es6 class mocks
ES6 Class Mocks · Jest
May 7, 2026 - 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 ·
Code with Hugo
codewithhugo.com › jest-mock-spy-module-import
Jest Full and Partial Mock/Spy of CommonJS and ES6 Module Imports · Code with Hugo
October 15, 2019 - Spying on the import/mocking part of the module becomes possible in the following fashion (full code at examples/spy-module-esm-default/lib.jest-test.js): import db from './db'; import lib from './lib'; const {addTodo, getTodo} = lib; beforeEach(() => jest.clearAllMocks()); test('ESM Default Export > addTodo > inserts with new id', async () => { const dbSetSpy = jest.spyOn(db, 'set').mockImplementationOnce(() => {}); await addTodo({name: 'new todo'}); expect(dbSetSpy).toHaveBeenCalledWith('todos:1', {name: 'new todo', id: 1}); }); test('ESM Default Export > getTodo > returns output of db.get', async () => { const dbGetSpy = jest.spyOn(db, 'get').mockResolvedValueOnce({ id: 1, name: 'todo-1' }); const expected = { id: 1, name: 'todo-1' }; const actual = await getTodo(1); expect(dbGetSpy).toHaveBeenCalledWith('todos:1'); expect(actual).toEqual(expected); });