Open In App

ReactJS Test Renderer

Last Updated : 06 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Without using the DOM or a native mobile environment, this package offers a React renderer that can be used to convert React components to pure JavaScript objects.

In essence, this package streamlines the process of taking a screenshot of the platform view hierarchy (comparable to a DOM tree) produced by a React DOM or React Native component without the need for a browser or jsDOM.

Importing:

import TestRenderer from 'react-test-renderer'; // ES6
const TestRenderer = require('react-test-renderer'); // ES5 with npm

TestRenderer:

1. TestRenderer.create(): With the supplied React element, create a TestRenderer object. Even though it doesn’t use the real DOM, the component tree is fully rendered into memory so that you may make claims about it. a TestRenderer instance is returned.

Syntax:

TestRenderer.create(element, options);

2. TestRenderer.act(): Similar to react-dom/test-utils’ act() function, TestRenderer.act readies a component for assertions. Wrap calls to TestRenderer.create and TestRenderer.update using this version of the act() function.

Syntax:

TestRenderer.act(callback);

TestRenderer instance:

1. testRenderer.toJSON(): Return a representation of the rendered tree as an object. There are no user-written components in this tree; it only includes platform-specific nodes like <div> and <view>, along with their associated props. This is useful for testing snapshots.

Syntax:

testRenderer.toJSON()

2. testRenderer.toTree(): Return a representation of the rendered tree as an object. The representation includes the user-written components and is more thorough than the one offered by toJSON(). Unless you’re building your own assertion library on top of the test renderer, you probably don’t need this method.

Syntax:

testRenderer.toTree()

3. testRenderer.update(): Create a new root element and redraw the in-memory tree. At the root, this imitates a React update. The tree will be updated if the new element has the same type and key as the outgoing element.

Syntax:

testRenderer.update(element)

4. testRenderer.unmount(): The proper lifecycle events are triggered when the in-memory tree is unmounted.

Syntax:

testRenderer.unmount()

5. testRenderer.getInstance(): If one is available, return the instance corresponding to the root element. Since function components don’t have instances, this won’t work if the root element is one.

Syntax:

testRenderer.getInstance()

6. testRenderer.root: Returns the root “test instance” object that can be used to make claims about particular tree nodes.

Syntax:

testRenderer.root

TextInstance:

1. testInstance.find(): A single descendent test instance must return true for test(testInstance) to be found. Test(testInstance) will throw an exception if it does not return true for exactly one test instance.

Syntax:

testInstance.find(test)

2. testInstance.findByType(): Find one instance of the descendant test with the given type. It will generate an error if there is not exactly one test instance of the given type.

Syntax:

testInstance.findByType(type)

3. testInstance.findByProps(): With the given props, find a single descendent test instance. It will throw an error if there isn’t exactly one test instance with the given props.

Syntax: 

testInstance.findByProps(props)

4. testInstance.findAll(): Find all test instances that have been ancestors and have test(testInstance) return true.

Syntax:

testInstance.findAll(test)

5. testInstance.findAllByType(): Find every descendent test instance that matches the given type.

Syntax:

testInstance.findAllByType(type)

6. testInstance.findAllByProps(): Use the supplied props to locate all descendent test instances.

Syntax:

testInstance.findAllByProps(props)

7. testInstance.instance: The instance of the component that corresponds to this test instance. Due to the lack of instances in function components, it is only accessible for class components. It is a match for the provided component’s this value.

Syntax:

testInstance.instance

8. testInstance.type: The component type that this test instance’s component belongs to. For instance, a component with the name <Button/> has a type of Button.

Syntax:

testInstance.type

9. testInstance.props: The attributes that apply to this test instance. For instance, a <Button size=”small” /> component has { size: ‘small’} as props.

Syntax:

testInstance.props

10. testInstance.parent: This test instance’s parent test instance.

Syntax:

testInstance.parent

11. testInstance.children: This test instance’s children test instances.

Syntax:

testInstance.children

Creating React Project:

Step 1: To create a react app, install react modules through the npm command.

npm create-react-app project name

Step 2: After creating your react project, move into the folder to perform different operations.

cd project name

Step 3: Install the required module by running the below command in the terminal:

npm i react-test-renderer

Step 4: After creating the ReactJS application, import the following dependencies into your app.

import TestRenderer from 'react-test-renderer'; // ES6
const TestRenderer = require('react-test-renderer'); // ES5 with npm

Project Structure: The project structure should look like below:                                                

   

 

Example 1:

index.js

Javascript




import React from 'react';
import TestRenderer from 'react-test-renderer';
import App from './App';
  
const testRenderer = TestRenderer.create(<App />);
console.log(testRenderer.toJSON());


App.js

Javascript




import React from 'react';
  
class App extends React.Component {
    render() {
        return (
            <div>
                <h1>Hello World!</h1>
                <p>This is a test of the React Renderer.</p>
            </div>
        );
    }
}
  
export default App;


Step to Run Application: Open the terminal and type the following command.

npm start

Output:

 

Explanation:  We’re using the ReactTestRenderer from the react-test-renderer library to create a component and test its render output. The toJSON() method is used to get the JSON representation of the component.

Example 2:

App.js

Javascript




import TestRenderer from 'react-test-renderer';
  
function MyComponent() {
    return (
        <div>
            <SubComponent foo="bar" />
            <p className="my">Hello GFG</p>
        </div>
    )
}
  
function SubComponent() {
    return (
        <p className="sub">Sub</p>
    );
}
  
const testRenderer = TestRenderer.create(<MyComponent />);
const testInstance = testRenderer.root;
  
expect(testInstance.findByType(SubComponent).props.foo).toBe('bar');
expect(testInstance.findByProps({ className: "sub" }).children).toEqual(['Sub']);


index.js

Javascript




import TestRenderer from 'react-test-renderer';
  
function Link(props) {
    return <a href={props.page}>{props.children}</a>;
}
  
const testRenderer = TestRenderer.create(
    <Link page="https://www.instragram.com/">Facebook</Link>
);
  
console.log(testRenderer.toJSON());


Step to Run Application: Open the terminal and type the following command.

npm start

Output:

 

Explanation:  we’re using the ReactTestRenderer from the react-test-renderer library to create a component and test its render output. The toJSON() method is used to get the tree representation of the component.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads