Testing your React components (part 2)

Victor Ferraz
May 21, 2019
<p>Disclaimer: due to the amount of information, this article is divided into three parts. The first part consists of a small intro to React testing, which includes configuration and snapshot/state changes tests. The second part shows how to test components using mocks and the third part brings more complex test cases with components that are using <a href="https://redux.js.org">redux</a>.</p><p>Welcome back! In my <a href="https://www.vinta.com.br/blog/2018/testing-your-react-components-part-1/">last article</a>, we talked about the basics of React testing with Jest and Enzyme - but that was just a small example of the things you can do with tests. In this article, I'll dive a little deeper and present to you the concepts of mocks and how Jest makes it pretty easy to work with them. If you're interested in the source code for this article (including all of its parts), you can get it <a href="https://github.com/victorfsf/jest-enzyme-examples">here</a>.</p><h2 id="packages-and-configuration">Packages and configuration</h2><p>Since Jest comes with complete mock support, you won't need to install anything more than what has already been mentioned in the previous article, which you can read <a href="https://www.vinta.com.br/blog/2018/testing-your-react-components-part-1/">here</a> (please note that we'll still be using Enzyme to render components). While I'll give you as much information as you'll need to get started and understand mocks, reading Jest's documentation on those is highly recommended, as they documented it pretty well. Here's a list of most of the mock-related pages from Jest's own documentation:</p><ul><li><a href="https://jestjs.io/docs/en/mock-functions">Mock functions</a></li><li><a href="https://jestjs.io/docs/en/manual-mocks">Manual mocks</a></li><li><a href="https://jestjs.io/docs/en/es6-class-mocks">ES6 class mocks</a></li><li><a href="https://jestjs.io/docs/en/bypassing-module-mocks">Bypassing module mocks</a></li><li><a href="https://jestjs.io/docs/en/mock-function-api">Mock function API</a></li></ul><p>Reading these pages after finishing this article will help you understand a lot more about the subject.</p><h2 id="what-is-a-mock">What is a "mock"?</h2><p>It can be very confusing to talk about mocks without understanding what they are and what they can do, so let's take this section to understand a little more about them; <em>if you already know what I'm talking about, feel free to jump to the next section</em>.</p><p>Mocks are nothing out of the ordinary and it's not an exclusive functionality of Jest or JavaScript – it's also present in test suites of many other programming languages. Basically, they replace a module/function/class/object with its mocked version. So, when I say that a function is a <em>mock</em> (or that it was <em>mocked</em>), it means that it's been replaced with a <em>fake</em> function that doesn't actually run anything and does not relate to its original code any longer. That would be applicable to anything you choose to mock. This doesn't sound like it's a useful feature, right? Well, when you mock something, you'll also have the power to <em>spy</em> on everything that it was asked to do (or everything that was done to it, such as how many times it was called and what arguments were passed in each call). You'll also be able to change and control what it returns or when it'll return something – or even replace its whole implementation.</p><h3 id="when-you-should-use-mocks">When you should use mocks</h3><p>There are several cases in which you can choose to use mocks. The most common cases though, are the ones when:</p><p>You want to isolate a specific function that have too many dependencies to determine its output (as in when they call other functions inside them). Now, when you're doing unit tests, there are times when you don't care about the results of other functions, except the one that you're actually testing. And that's where the mocks come in: if you mock them, you won't have to care about their results anymore, as they can be whatever you want; so an API call can always return what you tell it to return without actually asking the server, for example, and you won't have to wait for some other function that takes a very long time to run when you're not even testing it directly.</p><p>You want to keep count and be sure of how many times a function has been called and what were the arguments passed to it. Sometimes it's very important to know that the form is only calling <code>onSubmit</code> once and only once, or that you're passing the right arguments to do so.</p><h2 id="jest-mocks">Jest mocks</h2><p>As mentioned before, Jest comes with mock support by default. So if you want to mock something, there are four ways to do so:</p><p>By mocking a function</p><pre><code>const mockFunction = jest.fn(); </code></pre><p>By spying on a function from an external module</p><pre><code>const mockValidate = jest.spyOn(utils, 'validateString'); </code></pre><p>By mocking a module</p><pre><code>jest.mock('./utils.js'); </code></pre><p>By creating a <code>__mock__</code> folder that will replace a whole module's implementation creating a file with the same name as that module's name inside that folder.</p><p><code>jest.fn</code> should be enough for most React components, since you'll probably want to mock functions that are passed as props to them when they are instantiated, like <code>onClick</code>. <strong>With that said, this will be the main focus of the article.</strong></p><h3 id="when-not-to-use-mocks">When not to use mocks</h3><p>As magical as mocks are, there is always a limit. They should mostly be used as a secondary tool for testing and should never be used to mock your primary test objective. For example, this does not aggregate any value for your test suite:</p><pre><code>test('validateString returns false', () =&gt; { // mock the validateString function (imported through the utils module) const mockedValidateString = jest.spyOn( utils, 'validateString' ).mockReturnValue(false); const result = mockedValidateString(); // check if it'll return false, as specified by the mock expect(result).toBeFalsy(); mockedValidateString.mockRestore(); }); </code></pre><p>This will not aggregate anything either:</p><pre><code>test('api call returns expected body', () =&gt; { const expected = [{ id: 1, username: 'user' }]; // Mocks an API function called getAllUsers, // so it won't call the actual API to get the results jest.spyOn(api, 'getAllUsers').mockReturnValue(expected); // calls a function that will eventually call getAllUsers and return its result const result = anotherFunction(); expect(result).toHaveBeenCalledTimes(1); expect(result).toEqual(expected); }); </code></pre><p>Both cases do the exact same thing: <em>mock a function, then call it directly and check for its result</em>. Even though there is an obvious redundancy here, sometimes it's not that clear.</p><h3 id="overusing-mocks">Overusing mocks</h3><p>Another possible problem is the overuse of mocks. If you're not sure of what you should mock, it may be best to not do it at all or you might end up mocking everything you could and then your code will be completely <strong>tainted</strong>. This usually happens when you use <code>jest.fn/jest.mock/jest.spyOn</code> many times without assigning it to anything, just for the sake of stopping a certain module or function from working, or when you've simply mocked everything you could – and both cases could result in:</p><p>The code changing so much through mocks that the way it works is completely different and that might yield different results from its original version, even with the same inputs.</p><p>Mocking a function that is no longer being called because you've also mocked the function that calls it, rending the first function completely useless (this also falls under the redundancy case).</p><p>The best way to avoid these cases (both the redundancy and the overuse) is to <em>always be sure that you have a reason for mocking something</em>. So, I'll repeat - if the use of mocks doesn't really aid you in any way to achieve your test's objective, it may be better not to use it at all (or at least not in the way you're using).</p><h3 id="code-examples">Code examples</h3><p>All of the code examples that appear here come from <a href="https://github.com/victorfsf/jest-enzyme-examples/">this repository</a> and the link below each code block takes you to their proper file and line number, as the version of the code in this article was simplified for the sake of readability (see the <code>View on Github</code> links). You can also find more test examples in the repository.</p><p>All of the examples will be based on the test cases for the following components:</p><pre><code>class Tag extends Component { toggleFormOpen() { const { isFormOpen } = this.state; this.setState({ isFormOpen: !isFormOpen, }); } handleSubmit(e, name) { this.setState({ name }); } render() { const { isFormOpen, name } = this.state; const toggleForm = () =&gt; this.toggleFormOpen(); return isFormOpen ? ( &lt;TagForm name={name} onCancel={toggleForm} onSubmit={(e, values) =&gt; this.handleSubmit(e, values)} /&gt; ) : ( &lt;button className={classnames(styles.tag, styles.clickable)} onClick={toggleForm} type="button" &gt; {name} &lt;/button&gt; ); } } </code></pre><p>[<a href="https://github.com/victorfsf/jest-enzyme-examples/blob/master/src/app/components/Tag/Tag.js#L8">View on Github</a>]</p><pre><code>class TagForm extends Component { handleSubmit(e) { e.preventDefault(); const { onSubmit, onCancel } = this.props; const { value } = this.state; if (validateString(value)) { onSubmit(e, value); onCancel(); } } handleChange(e) { const { value } = e.target; this.setState({ value }); } render() { const { onCancel } = this.props; const { value } = this.state; return ( &lt;form onSubmit={e =&gt; this.handleSubmit(e)}&gt; &lt;input type="text" id="name" onChange={e =&gt; this.handleChange(e)} value={value} maxLength={35} /&gt; &lt;button type="button" onClick={onCancel}&gt;✖&lt;/button&gt; &lt;/form&gt; ); } } </code></pre><p>[<a href="https://github.com/victorfsf/jest-enzyme-examples/blob/master/src/app/components/Tag/TagForm.js#L10">View on Github</a>]</p><p>[newsletter widget]</p><h3 id="mocking-with-jest-fn">Mocking with <code>jest.fn</code></h3><p>As I've mentioned before, the simplest and most practical way to mock something is by using <code>jest.fn()</code>. This approach is perfect when you have outside access to the function you want to mock. See the example below:</p><pre><code>// TagForm.spec.js test('calls onCancel when ✖ is clicked', () =&gt; { const mockedOnCancel = jest.fn(); const wrapper = shallow(&lt;TagForm name="test" onSubmit={jest.fn()} onCancel={mockedOnCancel} /&gt;); wrapper.find('button[type="button"]').at(0).simulate('click'); expect(mockedOnCancel).toHaveBeenCalledTimes(1); }); </code></pre><p>[<a href="https://github.com/victorfsf/jest-enzyme-examples/blob/master/src/app/components/Tag/tests/TagForm.spec.js#L19">View on Github</a>]</p><p>In this case, the function is passed as a prop to the component, the first being called if a certain event occurs. Since you have the freedom here to pass whatever you want to <code>onCancel</code>, passing a mocked function by using <code>jest.fn()</code> is all that needs to be done.</p><p>The purpose of this test is to check whether <code>onCancel</code> is called when the cancel button is clicked. Outside the test scenario, <code>onCancel</code> should close the form without saving the changes and return to its view mode state (the <code>Tag</code> component) - but since we've replace its original function with a <code>mockedOnCancel</code> implementation, that behavior doesn't matter anymore and all we want is the call count of our mock after the click:</p><pre><code>// Click the cancel button wrapper.find('button[type="button"]').at(0).simulate('click'); // Check if onCancel was called exactly 1 time expect(mockedOnCancel).toHaveBeenCalledTimes(1); </code></pre><p>Now, let's say you want to check whether some functions are called when the form fails to submit. In this case you don't want them to be called, so you need to be sure that they won't do so. The purpose here is to check if the form stops the user from saving a tag with an empty name:</p><pre><code>test('doesnt call onSubmit/onCancel when the form is submitted and name.length === 0', () =&gt; { const mockedOnSubmit = jest.fn(); const mockedOnCancel = jest.fn(); const wrapper = shallow(&lt;TagForm name="test" onSubmit={mockedOnSubmit} onCancel={mockedOnCancel} /&gt;); wrapper.find('input#name').simulate('change', { target: { id: 'name', value: '', }, }); wrapper.find('form').simulate('submit'); expect(mockedOnSubmit).not.toHaveBeenCalled(); expect(mockedOnCancel).not.toHaveBeenCalled(); }); </code></pre><p>[<a href="https://github.com/victorfsf/jest-enzyme-examples/blob/master/src/app/components/Tag/tests/TagForm.spec.js#L64">View on Github</a>]</p><p>There are two functions that are called when the form is submitted: <code>onSubmit</code> which does the actual submitting, and <code>onCancel</code> which will return to the <code>Tag</code> component, but expected changes added.</p><p>First you need to simulate the events, so you should change the input value to <code>''</code> and then simulate the form's submission.</p><pre><code>wrapper.find('input#name').simulate('change', { target: { id: 'name', value: '', }, }); wrapper.find('form').simulate('submit'); </code></pre><p>Once the changes have been made, you can call <code>.not.toHaveBeenCalled()</code> for each function to test if they were <strong>not</strong> called (Jest handles negations by using the <code>.not</code> object, so everything after <code>.not</code> will be negated).</p><pre><code>expect(mockedOnSubmit).not.toHaveBeenCalled(); expect(mockedOnCancel).not.toHaveBeenCalled(); </code></pre><p>So if there's no input to save (as in, if <code>name.trim().length === 0</code>) <code>onCancel</code> and <code>onSubmit</code> should not be called, since the user should not be able to leave the form unless they click on the actual cancel button.</p><h3 id="mocking-a-component-s-instance-method">Mocking a component's instance method</h3><p>Enzyme's API has a method that can be used to access the component's instance object (called <code>.instance()</code>) which can be used to access all of its methods, including the ones you implement inside the component's class. See the code below:</p><pre><code>test('calls this.handleChange when the input changes', () =&gt; { const mockedHandleChange = jest.fn(); const wrapper = shallow(&lt;TagForm name="test" onSubmit={jest.fn()} onCancel={jest.fn()} /&gt;); wrapper.instance().handleChange = mockedHandleChange; ['new value', 'another new value', 'last new value'].forEach((value) =&gt; { wrapper.find('input#name').simulate('change', { target: { id: 'name', value, }, }); }); expect(mockedHandleChange).toHaveBeenCalledTimes(3); }); </code></pre><p>[<a href="https://github.com/victorfsf/jest-enzyme-examples/blob/master/src/app/components/Tag/tests/TagForm.spec.js#L90">View on Github</a>]</p><p>There are three things happening here:</p><ul><li>We're mocking but not using both <code>onCancel</code> and <code>onSubmit</code> functions.</li><li>We're mocking the instance's <code>handleChange</code> method.</li><li>We're testing that method by running a bulk of changes.</li></ul><p>If you only want to stop a function from actually running, its mock doesn't necessarily need to be used after its creation, as seen in the example below:</p><pre><code>const wrapper = shallow(&lt;TagForm name="test" onSubmit={jest.fn()} onCancel={jest.fn()} /&gt;); </code></pre><p><em>Always be aware of what you're doing, or you may end up mocking things there are not supposed to be mocked and that may alter or taint your test results.</em></p><p>Now you just need to test if <code>handleChange</code> is being called correctly with the correct amount of times, so the first thing you should do is to mock it:</p><pre><code>const mockedHandleChange = jest.fn(); wrapper.instance().handleChange = mockedHandleChange; </code></pre><p>But sometimes testing if a mock is called only once may not give you the certainty that you expect from a test. So you can do a bulk of changes and see how <code>handleChange</code> will behave:</p><pre><code>['new value', 'another new value', 'last new value'].forEach((value) =&gt; { wrapper.find('input#name').simulate('change', { target: { id: 'name', value, }, }); }); expect(mockedHandleChange).toHaveBeenCalledTimes(3); </code></pre><p>As you can see, three changes (<code>['new value', 'another new value', 'last new value']</code>) result in three different calls to <code>handleChange</code>, which is what we were expecting.</p><h3 id="testing-each-mock-function-call-separately">Testing each mock function call separately</h3><p>Let's consider the logic from the previous test code with some small changes:</p><pre><code>test('calls handleChange 5 times with different arguments each time', () =&gt; { const mockedHandleChange = jest.fn(); const wrapper = shallow(&lt;TagForm name="test" onSubmit={jest.fn()} onCancel={jest.fn()} /&gt;); wrapper.instance().handleChange = mockedHandleChange; const values = [ 'new value 1', 'new value 2', 'new value 3', 'new value 4', 'new value 5', ]; values.forEach((value) =&gt; { wrapper.find('input#name').simulate('change', { target: { id: 'name', value, }, }); }); expect(mockedHandleChange).toHaveBeenCalledTimes(5); const { calls } = mockedHandleChange.mock; expect(calls).toHaveLength(5); calls.forEach((call, i) =&gt; ( expect(call).toEqual([ { target: { id: 'name', value: values[i] } }, ]) )); }); </code></pre><p>[<a href="https://github.com/victorfsf/jest-enzyme-examples/blob/master/src/app/components/Tag/tests/TagForm.spec.js#L111">View on Github</a>]</p><p>In this case we're testing the exact same function, <code>handleChange</code>, but with a different approach: this time we want to know exactly which argument was given to the function and when. To do so, we can break this <code>forEach</code> loop down to five simple statements:</p><pre><code>// For consistency, you have to pass the arguments as a list, even if it's just one argument. expect(calls[0]).toEqual([{ target: { id: 'name', value: 'new value 1' } }]); expect(calls[1]).toEqual([{ target: { id: 'name', value: 'new value 2' } }]); expect(calls[2]).toEqual([{ target: { id: 'name', value: 'new value 3' } }]); expect(calls[3]).toEqual([{ target: { id: 'name', value: 'new value 4' } }]); expect(calls[4]).toEqual([{ target: { id: 'name', value: 'new value 5' } }]); </code></pre><p>All that these statements do is <em>get the mocked function's nth call and check if it was called with the expected arguments</em>.</p><h3 id="spying-with-jest-spyon">Spying with <code>jest.spyOn</code></h3><p>Sometimes we need to test a component that calls an external helper function which is imported from another module. But with the way that mocks work, mocking this helper would be a very complicated task if we used <code>jest.fn</code>. Thankfully, jest comes with a very simple solution called <code>spyOn</code>:</p><pre><code>import * as utils from 'app/utils'; // some hidden test codes describe(..., () =&gt; { test('doesnt submit the form when validateString returns false', () =&gt; { const mockedValidateString = jest.spyOn(utils, 'validateString').mockReturnValue(false); const mockedOnSubmit = jest.fn(); const wrapper = shallow(&lt;TagForm name="test" onSubmit={mockedOnSubmit} onCancel={jest.fn()} /&gt;); wrapper.find('form').simulate('submit', { preventDefault: jest.fn(), }); expect(mockedValidateString).toHaveBeenCalledTimes(1); expect(mockedOnSubmit).not.toHaveBeenCalled(); mockedValidateString.mockRestore(); }); }); </code></pre><p>[<a href="https://github.com/victorfsf/jest-enzyme-examples/blob/master/src/app/components/Tag/tests/TagForm.spec.js#L183">View on Github</a>]</p><p>If we break this down into parts, this is what we get:</p><pre><code>import * as utils from 'app/utils'; </code></pre><p>The whole utils module was imported here just so we can reference it as the first argument of the <code>spyOn</code> method:</p><pre><code>const mockedValidateString = jest.spyOn(utils, 'validateString').mockReturnValue(false); </code></pre><p>Then, since <code>validateString</code> is a function inside the <code>utils</code> module, we can create a mocked version of it without having to actually pass it to the component, since we are already importing it inside the component's file:</p><pre><code>// TagForm.js import { validateString } from 'app/utils'; </code></pre><p>So we can just check whatever we need to and then restore the function to its original code, clearing the mock:</p><pre><code>expect(mockedValidateString).toHaveBeenCalledTimes(1); mockedValidateString.mockRestore(); </code></pre><h3 id="other-mocking-techniques">Other mocking techniques</h3><p>You can do a lot of things when testing with mocks, more than I could possibly present in just one post. Keep in mind though, that Jest's documentation has some pretty good guides to help you out in specific cases, like <a href="https://jestjs.io/docs/en/manual-mocks">manual mocks</a>, <a href="https://jestjs.io/docs/en/es6-class-mocks">ES6 class mocks</a> and <a href="https://jestjs.io/docs/en/bypassing-module-mocks">bypassing module mocks</a> – all three were cited in the <strong>Packages and configurations</strong> section of this article.</p><h2 id="and-that-s-it-let-s-recap-everything-we-ve-learned-here-">And that's it! Let's recap everything we've learned here:</h2><ul><li>You can use mocks to block or mimic a module/function's behavior.</li><li>You can use mocks to simulate a module/function's result.</li><li>You should always be sure that you're not writing redundant test cases with mocks.</li><li>Don't overuse mocks or your tests may not work in the same way the original code does.</li><li>If the use of mocks doesn't really aid you in any way to achieve your test's objective, it may be better not to use it at all.</li><li>There are four basic ways to mock with Jest; we covered <code>jest.fn</code> and <code>jest.spyOn</code>, but you can check the documentation and go for <code>jest.mock</code> or yet a mock file inside a <code>__mock__</code> folder.</li><li>There are many ways to approach your tests cases with mocks and it doesn't really matter which one you choose as long as it meets your requirements.</li><li>Reading Jest's documentation is always a good start, not only with mocks, but with everything test-related.</li></ul><h2 id="coming-next">Coming next</h2><p>The third part of this article will include test cases with <code>redux</code> and how the approach changes with it.</p><p>Thanks to <a href="https://www.vinta.com.br/blog/author/arineto/">Arimatea Neto</a>, <a href="https://www.vinta.com.br/blog/author/vanessa/">Vanessa Barreiros</a> and <a href="https://cuducos.me/">Eduardo Cuducos</a> for reviewing this post!</p>