Jest mock react context : <p>I need some help understanding how one can test an application using <code>React</code> <code>Context</code>.</p>

<p>Here's my sample setup.</p>

<p><strong>context.js</strong></p>

<pre><code>import React from 'react'

export const AppContext = React.createContext()
</code></pre>

<p><strong>App.js</strong></p>

<pre><code>import React from 'react'

import MyComponent from './MyComponent'
import {AppContext} from './context'

const App extends React.Component {

  state = {
    items: []
  }

  handleItemAdd = newItem =&gt; {
    const {items} = this.state
    items.push(newItem)
    this.setState(items)
  }

  render() {
    return (
      &lt;AppContext.Provider value={{
        addItem: this.handleItemAdd
      }}&gt;
        &lt;MyComponent /&gt;
      &lt;/AppContext.Provider&gt;
    )
  }
}

export default App
</code></pre>

<p><strong>MyComponent.js</strong></p>

<pre><code>import React from 'react'

import {AppContext} from './context'

const MyComponent extends React.Component {    
  render() {
    return (
      &lt;AppContext.Consumer&gt;
        {addItem =&gt; 
          &lt;button onClick={() =&gt; addItem('new item')}&gt;
            Click me
          &lt;/button&gt;
        }
      &lt;/AppContext.Consumer&gt;
    )
  }
}

export default MyComponent
</code></pre>

<p>This is a simplified example. Imagine that there are more layers between <code>App</code> and <code>MyComponent</code>, hence the use of <code>React</code> <code>Context</code>.</p>

<p>And here's my test file for <code>MyComponent</code>.</p>

<p><strong>MyComponent.test.js</strong></p>

<pre><code>import React from 'react'
import {render, fireEvent} from 'react-testing-library'

test('component handles button click', () =&gt; {
  const {getByText} = render(
    &lt;MyComponent /&gt;
  )
  const button = getByText('Click me')
  fireEvent.click(button)
  expect...?
}
</code></pre>

<p>The thing is, <code>AppContext.Consumer</code> is part of the implementation of <code>MyComponent</code>, so in this test I don't have direct access to it. How do I mock <code>AppContext.Consumer</code> so I am actually able to verify that clicking a button fires a function call?</p>

<p>I know that in theory I can test this by rendering <code>MyComponent</code> in my <code>App</code>, but I want to write a unit test for <code>MyComponent</code> only.</p>
