Tuesday, March 10, 2020

Unit Testing React Application using Jest and Enzyme

Why Unit Testing

Testing code is probably one of the most important things to do in software engineering. Testing ensures the quality of what we are building. There are many ways to test code, from end-to-end testing (manual testing) to unit testing (component testing in React)
  • It makes process Agile
  • Improves quality of code
  • Issues can be found at early stage
  • Facilitates changes and Simplifies Integration
  • Provide Documentation
  • Debugging Process
  • Design
  • Reduce the cost

Test Pyramid

Test Pyramid
In Agile frameworks, automated testing can be grouped into a testing pyramid. A testing pyramid illustrates when we should use one testing method versus another. The pyramid shows that many unit-snapshot tests can be used to validate one integration test, and many integration tests can be used to validate one manual test.


Manual Testing

Manual Testing is a process of finding out the defects or bugs in a software program. In this method the tester plays an important role of end user and verifies that all the features of the application are working correctly.


End-to-end test: manual testing of the whole application. 
The idea of choosing what type of tests should be used is important, as we may be testing the same thing in two or three different levels of the pyramid.


Manual testing is slow and unsustainable. This type of testing works for our front-end applications because it mimics how the user will interact with our application. The problem with this testing is that it is expensive to maintain (any minor UI change may break the tests, because these tests are normally done with Selenium, a web browser emulator) and the time to develop one of this tests may be high. It’s important to note that we don’t usually use this type of testing in front-end applications due to high costs.


Integration Testing


Integration Testing is a level of software testing where individual units are combined and tested as a group. The purpose of this level of testing is to expose faults in the interaction between integrated units.
Integration testing may be good to test connections between components and finding bugs in these connections.The cost of maintaining and doing these tests is not very high and will test parts that we don’t test with unit tests.


Unit Testing


Unit Testing is a level of software testing where individual units/ components of a software are tested. The purpose is to validate that each unit of the software performs as designed. A unit is the smallest testable part of any software. It usually has one or a few inputs and usually a single output.

Unit/Snapshot testing is probably the easiest way to test components. It only focuses on one isolated item and its logic. If it follow the presentation-functional components division, it will even be easier to test this. 
For presentational components, it give the props to the component and expect a specific render (could be a good use case for snapshot). 


In functional testing, the tests can be more tricky. We need to mock a redux store to create user actions, and we expect redux actions to be called by the mocked store while we simulate events.



Why Jest

Jest is a testing framework created by Facebook. Facebook uses it to test JavaScript and React code. It was created under the premise of performance, features and adaptability. Jest provides an integrated “zero-configuration” experience. This is a differentiator from other popular testing frameworks like Mocha. Some of the killer features are:



  • Instant Feedback: Immersive Watch mode only runs test files related to changed files.
  • Fast and sandboxed: It runs parallel tests across workers, and buffers console messages and prints them together.
  • Snapshot Testing: Capture snapshots of React trees or other serializable values to simplify testing and analyze how state changes over time.
  • Built-in code coverage reports: Supports coverage for bringing out of the box coverage reports.
  • Zero configuration


Why Enzyme


Enzyme is a JavaScript Testing utility for React that makes it easier to test your React Components' output. You can also manipulate, traverse, and in some ways simulate runtime given the output.
Enzyme's API is meant to be intuitive and flexible by mimicking jQuery's API for DOM manipulation and traversal.



  • Convenient utilities to work with shallow rendering, static rendered markup or DOM rendering.
  • jQuery-like API to find elements, read props, etc.

  • Enzyme has three methods for rendering React components. These methods give different results and we use them in different cases. 

    Shallow: Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that tests aren’t indirectly asserting the behavior of child components. (Recommended)

    Mount: Full rendering and it doesn’t need an environment like a “browser”. This is useful when you want to test the children with less overhead than mount.

    Render: Full DOM rendering is ideal for use cases where you have components that may interact with DOM APIs. Full rendering actually mounts the component in the DOM. This is the only way to test componentDidMount and componentDidUpdate.

    Some Code Snippets :





    Snapshot Testing



    A snapshot test is essentially what the name implies. Jest takes the component that it is testing, renders it, and then takes a snapshot of what the component should look like. Everytime you run the test suite, Jest will do the process over again and compare the old snapshot to a new one. If the snapshots do not match, then they an error message shows in the terminal and highlights the parts that do not match.

    snapshot testing is not TDD, it can still be a useful tool for keeping track of your components and making sure they do not change unexpectedly.



    When to write a snapshot test


    • If a component is not updated often
    • If a component is not too complex
    • If it is easy to see what you are actually testing









        Async :





        Error Handling :




    Jest Command Line


    Run all tests : jest
    Run Specific test : jest path/to/my-test.js
    Run watch mode : jest --watch #runs jest -o by default jest --watchAll #runs all tests
    Coverage : jest --collectCoverage jest --collect-coverage
    Updating Snapshot : jest --updateSnapshot



    Useful Links