title: In a React/Jest unit test, how do you simulate an event prop being called by a mocked component?
body: <p>Suppose I have a React component that is a Login form with a Username field. If the user sets the Username to a blank string, the component shows an error message.</p>
  
  <p>Here's the code:</p>
  
  <pre><code>const LoginForm = () =&gt; {
    const [errorMessage, setErrorMessage] = useState(''),
      handleOnChangeUsername = (newUsername: string) =&gt; {
        if (newUsername.trim() === '') {
          setErrorMessage('Username is required.');
        } else {
          setErrorMessage('');
        }
      };
  
    return (
      &lt;form&gt;
        &lt;UsernameField onChange={handleOnChangeUsername} /&gt;
        {errorMessage &amp;&amp; &lt;Error message={errorMessage} /&gt;}
      &lt;/form&gt;
    );
  };
  </code></pre>
  
  <p>I want to unit test this component.</p>
  
  <p>So I want to write a test that verifies that when the user enters a blank username, then the error message: 'Username is required' is displayed underneath.</p>
  
  <p>In order to write this unit-test, I assume that I need to do the following:</p>
  
  <ol>
  <li><p>Mount the LoginForm component, providing a mocked UsernameField component.</p></li>
  <li><p>Get the mocked UsernameField component to call its onChange prop, passing in a blank string.</p></li>
  <li><p>Assert that the LoginForm component is now rendering an Error component (i.e. that the code in handleOnChangeUsername actually ran and produced the correct side-effect).</p></li>
  </ol>
  
  <p>The mocking part is easy – I just call jest.mock(...), passing in the path to the module and a mock implementation.</p>
  
  <p>The tricky bit is Step 2. How do I make my unit test cause the mock to call one of its own props, to simulate the onChange being called with an empty string?</p>
  
  <p>It seems like there would have to be some channel by which the unit test code could communicate with the internal props of the mocked component.</p>
  
  <p>Is there a simple and/or idiomatic way to do this in a React/Jest unit test?</p>
  
  <p>Note: This question assumes a <a href="https://martinfowler.com/articles/mocksArentStubs.html#ClassicalAndMockistTesting" rel="nofollow noreferrer">mockist style</a>. I know that some developers might say that I should simply trigger the Username onChange directly, by manipulating the DOM element that the Username component renders. I already know how to do that. But I want to follow a mockist style and completely mock the Username component.</p>