Table of contents
1.
Introduction
2.
Shallow Rendering API
3.
shallow(node[, options]) => ShallowWrapper
4.
ShallowWrapper API
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

ShallowWrapper API Reference

Author Parth Jain
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

When it comes to coding in React, Enzyme is one of the most popular JavaScript Testing utilities used to test a Components output. With Enzyme, it is possible to manipulate, traverse and simulate runtime for a given output.
Enzyme’s API is highly intuitive and flexible as it mimics jQuery’s API responsible for DOM manipulation.
This blog will help you understand a rendering technique in Enzyme called Shallow Rendering along with the use of Shallow Rendering API.                             

Shallow Rendering API

Shallow Rendering is a unique process that constrains testing a component as a single unit. This method ensures that the tests aren't indirectly asserting the behavior of a child component. 

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

describe('<MyComponent />', () => {
  it('renders three <Foo /> components', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.find(Foo)).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(<Foo onButtonClick={onButtonClick} />);
    wrapper.find('button').simulate('click');
    expect(onButtonClick).to.have.property('callCount', 1);
  });
});

shallow(node[, options]) => ShallowWrapper

Arguments

  • node (ReactElement): The node to render
  • options (Object [optional]):
  • options.context: (Object [optional]): The Context which is to be passed to the component
  • options.disableLifecycleMethods: (Boolean [optional]): If true, the componentDidMount is not called for that component, and the componentDidUpdate isn’t called after setProps and setContext. The Default value is set to false.
  • options.wrappingComponent: (ComponentType [optional]): A component that will be rendered as a parent of the node. It is used to provide context to the node.
  • options.wrappingComponentProps: (Object [optional]): Initial props to pass to the wrappingComponent if it is specified.
  • options.suspenseFallback: (Boolean [optional]): If true, while rendering the Suspense, Enzyme will replace all the lazy components in children with fallback element prop. Otherwise, it won't handle the fallback of an inert component. The Default value is true. 

Returns
ShallowWrapper: A wrapper instance around the rendered output.

ShallowWrapper API

  • .find(selector) => ShallowWrapper

Finds each node in the tree(render tree) that matches the provided selector.

  • .findWhere(predicate) => ShallowWrapper

Finds each node in the tree(render tree) that returns true for the provided predicate function.

  • .filter(selector) => ShallowWrapper

Removes the nodes in the current wrapper that does not match with the provided selector.

  • .filterWhere(predicate) => ShallowWrapper

Removes all the nodes in the current wrapper that do not return true for the provided predicate function.

  • .hostNodes() => ShallowWrapper

Removes all the nodes that are not hosted nodes.

  • .contains(nodeOrNodes) => Boolean

Returns if a given node or an array of nodes is somewhere inside the render tree or not.

  • .containsMatchingElement(node) => Boolean

Returns if a given react element exists inside the shallow render tree.

  • .containsAllMatchingElements(nodes) => Boolean

Returns if all the given react elements exist inside the shallow render tree.

  • .containsAnyMatchingElements(nodes) => Boolean

Returns if one of the given react elements exists inside the Shallow render tree.

  • .equals(node) => Boolean

Returns if the current render tree is equal to the given node.

  • .matchesElement(node) => Boolean

Returns if a given react element matches with the shallow render tree.

  • .hasClass(className) => Boolean

Returns if the current node has the given class name or not.

  • .is(selector) => Boolean

Returns if the current node matches a provided selector or not.

  • .exists([selector]) => Boolean

Returns if the current node exists or, for a given selector, whether that selector has any matching results or not.

  • .isEmpty() => Boolean

This is Deprecated: Use .exists() instead.

  • .isEmptyRender() => Boolean

Returns if the current component returns a false value or not.

  • .not(selector) => ShallowWrapper

Remove all the nodes in the current wrapper that matches the provided selector. 

  • .children([selector]) => ShallowWrapper

Gets a wrapper with all of the child nodes of the current wrapper.

  • .childAt(index) => ShallowWrapper

Returns a new wrapper with the child at a specified index.

  • .parents([selector]) => ShallowWrapper

Gets a wrapper with all the parents of the current node.

  • .parent() => ShallowWrapper

Gets a wrapper with the direct parents of the current node.

  • .closest(selector) => ShallowWrapper

Gets a wrapper with the first parent of the current node to match with the provided selector.

  • .shallow([options]) => ShallowWrapper

This will Shallow render the current node and return a shallow wrapper around it.

  • .render() => CheerioWrapper

It will return a CheerioWrapper for the current node.

  • .renderProp(key)() => ShallowWrapper

It returns a wrapper of the node rendered by a provided render prop.

  • .unmount() => ShallowWrapper

It is a method that un-mounts a component.

  • .text() => String

It returns a string representation for the text nodes in the current tree(render tree).

  • .html() => String

It returns a static HTML rendering for the current node.

  • .get(index) => ReactElement

It returns the node at the provided index for the current wrapper.

  • .getElement() => ReactElement

This will return a wrapped ReactElement.

  • .getElements() => Array<ReactElement>

This will return a collection of wrapped ReactElements.

  • .at(index) => ShallowWrapper

It returns a wrapper of the node at the provided index for the current wrapper.

  • .first() => ShallowWrapper

It returns a wrapper of the first node for the current wrapper.

  • .last() => ShallowWrapper

This returns a wrapper of the last node for the current wrapper.

  • .state([key]) => Any

This will return the state of a root component.

  • .context([key]) => Any

It returns the context of the root component.

  • .props() => Object

Will return the props of the current node.

  • .prop(key) => Any

Will return the named prop for the current node.

  • .key() => String

It will return the key for the current node.

  • .invoke(propName)(...args) => Any

Will Invoke a prop function on the current node and return the function's return value.

  • .simulate(event[, data]) => ShallowWrapper

Will Simulate an event on the current node.

  • .setState(nextState) => ShallowWrapper

It will manually set the state for the root component.

  • .setProps(nextProps[, callback]) => ShallowWrapper

It will manually set the props of the root component.

  • .setContext(context) => ShallowWrapper

It will manually set the context of the root component.

  • .getWrappingComponent() => ShallowWrapper

Will return a wrapper representing the wrappingComponent if one was passed.

  • .instance() => ReactComponent

This will return the instance of the root component.

  • .update() => ShallowWrapper

It syncs the enzyme component tree's snapshot with the react component tree.

  • .debug() => String

Will Return a string representation of the current Shallow render tree.

  • .type() => String|Function|null

It returns the type of the current node of the wrapper.

  • .name() => String

Will return the name of the current node for the wrapper.

  • .forEach(fn) => ShallowWrapper

Will iterate through each node of the current wrapper and execute a provided function.

  • .map(fn) => Array

Will map the current array of nodes to another array.

  • .reduce(fn[, initialValue]) => Any

Will reduce the current array of nodes to a given value.

  • .reduceRight(fn[, initialValue]) => Any

Will reduce the current array of nodes to a given value from right to left.

  • .slice([begin[, end]]) => ShallowWrapper

It will return a new wrapper with a subset of the nodes of the original wrapper.

  • .tap(intercepter) => Self

It taps into the wrapper method chain.

  • .some(selector) => Boolean

Returns if any of the nodes in the wrapper match the provided selector or not.

  • .someWhere(predicate) => Boolean

Returns if any of the nodes in the wrapper pass the provided predicate function or not.

  • .every(selector) => Boolean

Returns if all of the nodes in the wrapper match the provided selector or not.

  • .everyWhere(predicate) => Boolean

Returns if all of the nodes in the wrapper pass the provided predicate function or not.

  • .dive([options]) => ShallowWrapper

Shallow renders the one non-DOM child of the current wrapper and returns a wrapper around the result.

FAQs

  1. What is Shallow Rendering?
    Shallow Rendering is a technique that allows a component to render one level deep while asserting facts about what it returns. Furthermore, with Shallow Rendering, we do not have to worry about the behavior of the child components.
  2. What is Shallow from Enzyme?
    The Shallow method is used to render a single component under testing. While under testing, It will not render child components.
  3. Does Shallow render call componentDidMount?
    As of Enzyme version 3, the shallow API does call the React lifecycle methods such as componentDidUpdate and componentDidMount.
  4. What is the difference between Rendering and mounting?
    Rendering happens whenever a function component gets called, while Mounting is when React renders the component for the first time and develops the initial DOM.
  5. Why is Shallow Rendering required?
    Shallow Rendering is a unique process that constrains testing a component as a single unit. This method ensures that the tests aren't indirectly asserting the behavior of a child component. 

Key Takeaways

In this article, we have extensively discussed the Shallow Rendering technique and the ShallowWrapper API in Enzyme.If you are Preparing for interview and don't know where to start, we have got you covered, check out our expert curated courses on our website, You can also check out Coding Ninjas Studio to practice frequently asked interview problems. We hope that this blog has helped you enhance your knowledge regarding Java and if you would like to learn more, check out our articles. Do upvote our blog to help other ninjas grow. Happy Coding!”

Live masterclass