[React Testing] Intro to Shallow Rendering

In this lesson, we walk through how to use one of React's Test Utilities (from thereact-addons-test-utils package) called "Shallow Rendering". This lets us render our React component one level deep - without a DOM - so that we can write tests for it. It works kind of like ReactDOM.render, where the shallow renderer is a temporary place to "hold" your rendered component so that you can assert things about its output. Tests written using the shallow renderer are great for stateless or "dumb" components that simply have their props passed to them from a parent container or "smart" component. These shallow renderer tests work especially well with stateless function components. They also work well for "unit" tests where you want to make sure your code works in isolation.

_NOTE: The React team has recommended composing the majority of your apps using these stateless "dumb" components, so the majority of lessons in this course will focus on writing simple unit tests for these stateless components using Shallow Rendering. If you also want to write tests for the stateful components that are tied to different components and state and can't be tested in isolation, you may want to look at using a DOM (with something like Karma or jsdom) and React's other test utilities like renderIntoDocument and Simulate. However, I've found that it is helpful to try to compose most of your project with simple, isolated, stateless or "pure" components that can be unit tested with Shallow Rendering, and then wrap these components with a few stateful or "impure" components that you can either not worry about testing (what I do most of the time because it is difficult to test stateful components), or write separate integration and functional tests for them using different tools.

复制代码
import React from 'react';
import expect from 'expect';
import TestUtils from 'react-addons-test-utils';

const CoolComponent = ({greeting}) => {
    return (
        <div>
            <h1>Greeting</h1>
            <div>{greeting}</div>
        </div>
    );
};

describe('CoolComponent', ()=>{

    it('should ...', ()=>{
        //Shallow Rendering
        const renderer = TestUtils.createRenderer();

        renderer.render(<CoolComponent greeting='hello world' />);
        const output = renderer.getRenderOutput();

        console.log(output);
    });
});
复制代码

 

It outputs:

复制代码
{ '$$typeof': Symbol(react.element),
  type: 'div',
  key: null,
  ref: null,
  props: { children: [ [Object], [Object] ] },
  _owner:
   { _currentElement:
      { '$$typeof': Symbol(react.element),
        type: [Function: CoolComponent],
        key: null,
        ref: null,
        props: [Object],
        _owner: null,
        _store: {} },
     _rootNodeID: '.atjgairf9c',
     _instance:
      StatelessComponent {
        props: [Object],
        context: {},
        refs: {},
        updater: [Object],
        _reactInternalInstance: [Circular],
        state: null },
     _pendingElement: null,
     _pendingStateQueue: null,
     _pendingReplaceState: false,
     _pendingForceUpdate: false,
     _renderedComponent: { _renderedOutput: [Circular], _currentElement: [Circular] },
     _context: {},
     _mountOrder: 1,
     _topLevelWrapper: null,
     _pendingCallbacks: null },
  _store: {} }
复制代码

 

posted @   Zhentiw  阅读(343)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2015-01-05 [MODx] 3. Working with chunks, TV, Category
2015-01-05 [MODx] 2. Install some useful packages into ur MODx
2015-01-05 [MODx] 1. Add Html5 template into the MODx
2015-01-05 [AngularJS]* Create a Scope Decorator
2015-01-05 [AngularJS]* $http transformRequest
点击右上角即可分享
微信分享提示