Jest: mocking console.error - tests fails : <p><strong>The Problem:</strong></p>

<p>I have a simple React component I'm using to learn to test components with Jest and Enzyme.  As I'm working with props, I added the <code>prop-types</code> module to check for properties in development.  <code>prop-types</code> uses <code>console.error</code> to alert when mandatory props are not passed or when props are the wrong data type.</p>

<p>I wanted to mock <code>console.error</code> to count the number of times it was called by <code>prop-types</code> as I passed in missing/mis-typed props.</p>

<p>Using this simplified example component and test, I'd expect the two tests to behave as such:</p>

<ol>
<li>The first test with 0/2 required props should catch the mock calling twice.</li>
<li>The second test with 1/2 required props should catch the mock called once.</li>
</ol>

<p>Instead, I get this:</p>

<ol>
<li>The first test runs successfully.</li>
<li>The second test fails, complaining that the mock function was called zero times.</li>
<li>If I swap the order of the tests, the first works and the second fails.</li>
<li>If I split each test into an individual file, both work.</li>
<li><code>console.error</code> output is suppressed, so it's clear it's mocked for both.</li>
</ol>

<p><strong><em>I'm sure I am missing something obvious, like clearing the mock wrong or whatever.</em></strong></p>

<p>When I use the same structure against a module that exports a function, calling <code>console.error</code> some arbitrary number of times, things work.  </p>

<p>It's when I test with enzyme/react that I hit this wall after the first test.</p>

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

<pre><code>import React, { Component } from 'react';
import PropTypes from 'prop-types';

export default class App extends Component {

  render(){
    return(
      &lt;div&gt;Hello world.&lt;/div&gt;
    );
  }
};

App.propTypes = {
  id : PropTypes.string.isRequired,
  data : PropTypes.object.isRequired
};
</code></pre>

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

<pre><code>import React from 'react';
import { mount } from 'enzyme';
import App from './App';

console.error = jest.fn();

beforeEach(() =&gt; {
  console.error.mockClear();
});

it('component logs two errors when no props are passed', () =&gt; {
  const wrapper = mount(&lt;App /&gt;);
  expect(console.error).toHaveBeenCalledTimes(2);
});

it('component logs one error when only id is passed', () =&gt; {
  const wrapper = mount(&lt;App id="stringofstuff"/&gt;);
  expect(console.error).toHaveBeenCalledTimes(1);
});
</code></pre>

<p><strong>Final note:</strong> Yeah, it's better to write the component to generate some user friendly output when props are missing, then test for that.  But once I found this behavior, I wanted to figure out what I'm doing wrong as a way to improve my understanding.  Clearly, I'm missing something.</p>
