1. react-shallow-renderer
React package for shallow rendering.
react-shallow-renderer
Package: react-shallow-renderer
Created by: NMinhNguyen
Last modified: Sun, 26 Jun 2022 08:11:47 GMT
Version: 16.15.0
License: MIT
Downloads: 16,060,583
Repository: https://github.com/NMinhNguyen/react-shallow-renderer

Install

npm install react-shallow-renderer
yarn add react-shallow-renderer

react-shallow-renderer

GitHub license
npm version
CircleCI

When writing unit tests for React, shallow rendering can be helpful. Shallow rendering lets you render a component "one level deep" and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered. This does not require a DOM.

Installation

 # npm
npm install react-shallow-renderer --save-dev

# Yarn
yarn add react-shallow-renderer --dev

Usage

For example, if you have the following component:

 function MyComponent() {
  return (
    <div>
      <span className="heading">Title</span>
      <Subcomponent foo="bar" />
    </div>
  );
}

Then you can assert:

 import ShallowRenderer from 'react-shallow-renderer';
// in your test:
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" />,
]);

Shallow testing currently has some limitations, namely not supporting refs.

Note:

We also recommend checking out Enzyme's Shallow Rendering API. It provides a nicer higher-level API over the same functionality.

Reference

shallowRenderer.render()

You can think of the shallowRenderer as a "place" to render the component you're testing, and from which you can extract the component's output.

shallowRenderer.render() is similar to ReactDOM.render() but it doesn't require DOM and only renders a single level deep. This means you can test components isolated from how their children are implemented.

shallowRenderer.getRenderOutput()

After shallowRenderer.render() has been called, you can use shallowRenderer.getRenderOutput() to get the shallowly rendered output.

You can then begin to assert facts about the output.

Dependencies

RELATED POST

10 Must-Know Windows Shortcuts That Will Save You Time

10 Must-Know Windows Shortcuts That Will Save You Time

Arrays vs Linked Lists: Which is Better for Memory Management in Data Structures?

Arrays vs Linked Lists: Which is Better for Memory Management in Data Structures?

Navigating AWS Networking: Essential Hacks for Smooth Operation

Navigating AWS Networking: Essential Hacks for Smooth Operation

Achieving Stunning Visuals with Unity's Global Illumination

Achieving Stunning Visuals with Unity's Global Illumination

Nim's Hidden Gems: Lesser-known Features for Writing Efficient Code

Nim's Hidden Gems: Lesser-known Features for Writing Efficient Code