Jim Lynch Codes
  • Blog
  • About Jim

Writings about one coder's stories & experiences.

Pro Tip: Use Async / Await With Act To Avoid Act Warnings in Jest / Enzyme Tests And Have Components Update Properly!

10/2/2019

0 Comments

 
Picture
I was having a hard time recently writing jest + enzyme unit tests for a react.js project, and one of my colleagues saved the day with the await / async addition. In this post I'll go through what I was doing, what I tried that didn't work, and what we ultimately went with that fixed everything!

The Ugly Act Warnings

Consider this code below. It may seem to you like a perfectly logical test that uses Enzyme to "mount" a CancelTaskComponent. The cancel component isn't just a single cancel button... come on guys, that's not cool! No, this cancel component has a cancel button that, when pressed, reveals a textarea for the user to provide a "cancellation reason", and a final submit button. After clicking the final submit button we expect our "datafetcher" service to call the backend with out cancellation reason and the cancellation textarea to be cleared out. Take a gander:
import React from 'react';
import configureMockStore from 'redux-mock-store';
import { act } from 'react-dom/test-utils';
import dotenv from 'dotenv';
import dataFetcherService from '../services/data-fetcher';
import config from '../config';
import CancelTaskButton from './cancel-task-button';
import { Provider } from 'react-redux';
import { mountWithStoreAndTheme } from './../test/with-providers';
dotenv.config();

describe('src/components/cancel-task-button.test', () => {
  let cancelTaskButton;
  const fakeTaskId = '123';
  const fakeCancellationReason = 'Oh mah bad, I made this task by mistake!';

  describe('clicking the cancel-task-button', () => {
    describe('when data fetching is successful', () => {
      it('dispatches response data to redux and clears the form.', async done => {
        // Given I'm a dispatcher on the show page.
        dataFetcherService.sendData = jest.fn().mockReturnValue({ data: { id: fakeTaskId } });
        const mockStore = configureMockStore();
        const store = mockStore({
          tasksReducer: {
            taskSelected: {
              id: fakeTaskId
            }
          }
        });
        const cancelTaskComponent = mount(
          <Provider store={store}>
            <CancelTaskComponent />
          </Provider>
        );

        // When I click cancel, fill out modal with cancellation reason, and then click save
        cancelTaskComponent.find('Button#cancel-task-btn').simulate('click');
        cancelTaskComponent
          .find('textarea')
          .props()
          .onChange({
            currentTarget: {
              value: fakeCancellationReason
            }
          });

        // Sanity check that it's correctly reading text in textarea.
        expect(cancelTaskComponent.find('textarea').text()).toBe(fakeCancellationReason);

        cancelTaskComponent.find('button#submit-cancellation-btn').simulate('click');

        // Then the /cancel endpoint should be called with the cancellation reason and textarea should be cleared out.
        expect(dataFetcherService.sendData).toHaveBeenCalledWith(
          `${config.app.backendApiUrl}/task/${fakeTaskId}/cancel`,
          {
            reason: fakeCancellationReason
          }
        );

        setImmediate(() => {
          expect(cancelTaskComponent.find('textarea').text()).toBe('');
          done();
        });
        dataFetcherService.sendData.mockClear();
      });
    });
  });
});
Interestingly, this code passes when I run it with Jest, but I get these gross red errors in my console even though the test was passing! Gad zooks, my dear!
Picture

Wrapping In "Bare Act" Didn't Work

After seeing this error, I went through my code and trie many combinations of things wrapped in this call to "act" which takes a anonymous function inside of which you put your "state updating code". unfortunately, this did not solve my issue. I tried to wrap the entire contents of my "it" block, but then why I ran the assertions it seemed that my components were not updating. AAaaarrrrgggh!! Wht can I do?

Use Async / Await Act

I forget how we originally figured this out, but a consistent way we found to relieve ourselves of this warning was to wrap our "state updating code" in these async / await versions of act. See the updated code below:
import React from 'react';
import configureMockStore from 'redux-mock-store';
import { act } from 'react-dom/test-utils';
import dotenv from 'dotenv';
import dataFetcherService from '../services/data-fetcher';
import config from '../config';
import CancelTaskComponent from './cancel-task-button';
import { Provider } from 'react-redux';
import { mount } from 'enzyme';
import ErrorMessage from './error-message';
dotenv.config();

describe('src/components/cancel-task-button.test', () => {
  let cancelTaskComponent;
  const fakeTaskId = '123';
  const fakeCancellationReason = 'Oh mah bad, I made this task by mistake!';

  describe('clicking the cancel-task-button', () => {
    describe('when data fetching is successful', () => {
      it('dispatches reponse data to redux and clears the form.', async done => {
        // Given I'm a dispatcher on the show page.
        dataFetcherService.sendData = jest.fn().mockReturnValue({ data: { id: fakeTaskId } });
        const mockStore = configureMockStore();
        const store = mockStore({
          tasksReducer: {
            taskSelected: {
              id: fakeTaskId
            }
          }
        });
        const cancelTaskComponent = mount(
          <Provider store={store}>
            <CancelTaskComponent />
          </Provider>
        );

        // When I click cancel, fill out modal with cancellation reason, and then click save
        await act(async () => {
          cancelTaskComponent.find('Button#cancel-task-btn').simulate('click');
          cancelTaskComponent
            .find('textarea')
            .props()
            .onChange({
              currentTarget: {
                value: fakeCancellationReason
              }
            });
        });

        // Sanity check that it's correctly reading text in textarea.
        expect(cancelTaskComponent.find('textarea').text()).toBe(fakeCancellationReason);

        await act(async () => {
          cancelTaskComponent.find('button#submit-cancellation-btn').simulate('click');
        });

        // Then the /cancel endpoint should be called with the cancellation reason and textarea should be cleared out.
        expect(dataFetcherService.sendData).toHaveBeenCalledWith(
          `${config.app.bolideApiUrl}/task/${fakeTaskId}/cancel`,
          {
            reason: fakeCancellationReason
          }
        );

        setImmediate(() => {
          expect(cancelTaskComponent.find('textarea').text()).toBe('');
          done();
        });
        dataFetcherService.sendData.mockClear();
      });
    });
 });
Picture
This above code is working nicely for me, updating the components correctly, and most importantly not throwing any nasty red act warnings! ​

Let me know how it works for you!
0 Comments

Your comment will be posted after it is approved.


Leave a Reply.

    ​Author

    Picture
    The posts on this site are written and maintained by Jim Lynch. About Jim...
    Follow @JimLynchCodes
    Follow @JimLynchCodes

    Want FREE access to
    my daily stock tips 
    ​newsletters??
    Sign up here:

    - Triple Gainers
    - Rippers N' Dippers
    - Growingest Growers
    ​

    Categories

    All
    Actionscript 3
    Angular
    AngularJS
    Automated Testing
    AWS Lambda
    Behavior Driven Development
    Blogging
    Business Building
    C#
    C / C++
    ClojureScript / Clojure
    Coding
    Community Service
    CS Philosophy
    Css / Scss
    Dev Ops
    Firebase
    Fitness
    Flash
    Front End
    Functional Programming
    Git
    Go Lang
    Haskell
    Illustrations
    Java
    Javascript
    Lean
    Life
    Linux
    Logic Pro
    Music
    Node.js
    Planning
    Productivity
    Professionalism
    Python
    React
    Redux / Ngrx
    Refactoring
    Reusable Components
    Rust
    Security
    Serverless
    Shell Scripting
    Swift
    Test Driven Development
    Things
    TypeScript
    Useful Sites
    Useful Tools
    Video
    Website Development
    WebStorm
    Writing

    Archives

    February 2021
    January 2021
    October 2020
    September 2020
    May 2020
    April 2020
    February 2020
    January 2020
    December 2019
    October 2019
    September 2019
    August 2019
    July 2019
    June 2019
    May 2019
    April 2019
    March 2019
    February 2019
    January 2019
    December 2018
    November 2018
    October 2018
    September 2018
    August 2018
    June 2018
    May 2018
    April 2018
    March 2018
    February 2018
    January 2018
    December 2017
    November 2017
    October 2017
    September 2017
    August 2017
    July 2017
    May 2017
    April 2017
    March 2017
    February 2017
    January 2017
    December 2016
    November 2016
    October 2016
    September 2016
    August 2016
    July 2016
    June 2016
    May 2016
    April 2016
    March 2016
    February 2016
    January 2016
    December 2015
    November 2015
    October 2015

    RSS Feed

  • Blog
  • About Jim
JimLynchCodes © 2021