Jest mock react context
You just render the context with your component.
const addItem = jest.fn()
render(
<AppContext.Provider value={{ addItem }}>
<MyComponent />
</AppContext.Provider>
)
See Mocking context with react-testing-library
I want to add a complete test example by using the solution from @Giorgio. Here we are testing that MyComponent is rendered and that its button will be clicked once.
MyComponent.test.js
import React from 'react'
import { render, fireEvent } from 'react-testing-library'
test('component handles button click', () => {
const addItem = jest.fn()
render(
<AppContext.Provider value={{ addItem }}>
<MyComponent />
</AppContext.Provider>
)
fireEvent.click(screen.getByText(/click me/))
expect(addItem).toHaveBeenCalledTimes(1)
}