Table of contents
1.
Introduction
2.
Shallow rendering
2.1.
Rendering div elements
3.
Why Shallow Rendering?
4.
Shallow Wrapper API
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Shallow rendering

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The enzyme is a JavaScript Testing utility for React that makes your React Component output's assertions, manipulations, and traversals easier. It adds additional utility methods for component rendering, finding elements, and interacting with them. Rendering displays our HTML elements and generates or modifies the content every time on a function call. React renders the HTML to the web page by using a function called render(). Let’s learn about shallow rendering using enzyme in React in this article.

Shallow rendering

Whenever we render a website statically or dynamically, we consider the whole application and test the entire application. But what if you want to render and test only a specific portion of the code and don’t impact the other parts? So to overcome this problem, we use shallow rendering in React.

Shallow rendering is a technique where you test a component as a unit and ensure that your tests aren't indirectly asserting the functionality of child components. We can also specify the function to be invoked for the testing. This does not require a DOM(Document Object Model). 

Let’s take an example of the code below for shallow rendering ‘div’ tags.

Rendering div elements

function MyComponent() {
  return (
    <div>
      <span className="heading">Title</span>
      <Subcomponent foo="bar" />
    </div>
  );
}
You can also try this code with Online Javascript Compiler
Run Code


Suppose we have a code with 'div' elements similar to that written above. In that case, we can render it by importing the ShallowRender into our code and creating an object for ShallowRender to access the methods inside it. 

import ShallowRenderer from 'react-test-renderer/shallow';


const renderer = new ShallowRenderer();
renderer.render(<MyComponent />);
const result = renderer.getRenderOutput();


expect(result.type).toBe('div');
expect(result.props.children).toEqual([
  <span className="heading">Title</span>,
  <Subcomponent foo="bar" />
]);


The render() function isolates the component from its children or linked components and then the method renderer.getRenderOutput() gives the result of the rendering function and then validates the result against the expected output using the expect() function.

Why Shallow Rendering?

Shallow rendering is better than mounting or general rendering as it is faster. It concentrates on the unit tests of a specific component without impacting its children or any linked components. Even if any child components test cases fail, they don’t impact the tests of the parent component if we use shallow rendering. So shallow() rendering is better and faster than mount() for isolated testing and rendering, but if you want to test the lifecycle hooks, you have to use mount() instead of render, as the hooks might need other components to be included too.

Shallow Wrapper API

The shallow wrapper API is used to render the components on lifecycle methods and mounting methods. It provides us with different functions in the wrapper class for rendering. Let’s learn how to code for a shallow wrapper rendering.

import { shallow } from 'enzyme';
import sinon from 'sinon';
import App from './App;

describe('<MyComponent />', () => {
  it('renders three <App /> components', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.find(App)).to.have.lengthOf(3);
  });

  it('renders an `.icon-star`', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.find('.icon-star')).to.have.lengthOf(1);
  });

  it('renders children when passed in', () => {
    const wrapper = shallow((
      <MyComponent>
        <div className="unique" />
      </MyComponent>
    ));
    expect(wrapper.contains(<div className="unique" />)).to.equal(true);
  });

  it('simulates click events', () => {
    const onButtonClick = sinon.spy();
    const wrapper = shallow(<App onButtonClick={onButtonClick} />);
    wrapper.find('button').simulate('click');
    expect(onButtonClick).to.have.property('callCount', 1);
  });
});


We imported the shallow method from the enzyme and our component App in the above code. We grouped all the functions and elements in the component. We gave different conditions for rendering like rendering the components, rendering the icons, rendering the children, and rendering the click events individually using the it() function. The wrapper API methods in our code perform the rendering and different functions. Let’s discuss a few methods with their descriptions.

Method Description
.find(selector) => ShallowWrapper Checks the render tree and finds the node that matches with the provided selector.
.filter(selector) => ShallowWrapper Removes the nodes that do not match the provided selector in the current wrapper.
.contains(nodeOrNodes) => Boolean Checks whether the given node/nodes is /are present in the render tree and returns true or false(boolean value).
.containsMatchingElement(node) => Boolean Checks whether all the given react elements exist in the shallow render tree and returns true or false.
.equals(node) => Boolean Checks whether the current render tree is equal to the given node, based on the expected value and returns true or false.
.exists([selector]) => Boolean Checks whether the current node or selector exists in the render tree or has any matching results.
.children([selector]) => ShallowWrapper Gets the wrapper of the children nodes of the current wrapper.
.parents([selector]) => ShallowWrapper Gets the wrapper of the parents of the current node.
.shallow([options]) => ShallowWrapper It shallow renders the current node and returns a shallow wrapper around it.
.getElement() => ReactElement Returns the wrapped ReactElement.

FAQs

  1. What is shallow rendering?
    Shallow rendering is a technique where you test a component as a unit and ensure that your tests aren't indirectly asserting the functionality of child components.
     
  2. Is Shallow rendering better than mounting?
    Shallow rendering is better than mounting in terms of components dependency and speed. But if you want to test all the components and methods, you have to use Shallow wrapper API or mounting.
     
  3. Does shallow render call componentDidMount?
    Yes, the Shallow API calls componentDidMount and other life cycle hooks along with click events. So you can render most of the elements in your code using shallow API.
     
  4. What is a Shallow wrapper?
    The shallow wrapper API is used to render the components on lifecycle methods and mounting methods. It provides us with different functions in the wrapper class for rendering. 
     
  5. What does the getRenderOutput() method do?
    The getRenderOutput() method gives you the output of shallow rendered elements. It is called after you call render() method, which isolates the component from its children.

Key Takeaways

We discussed the concept of shallow rendering and Enzyme. We have also learned a few examples of the code that you can use to test only a portion of the code and not the whole application. Then we discussed the shallow Wrapper API and the methods provided by it.

Hey Ninjas! We hope this blog helped you enhance your knowledge of shallow rendering. If you want to learn more, check out Coding Ninjas for more unique courses and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and fantastic Data Structures and Algorithms problems. Do upvote our blog to help the other ninjas grow.

Happy Learning!

Live masterclass