文档章节

Snapshot Tests in React Using Jest

Kolosek
 Kolosek
发布于 2018/03/19 17:18
字数 534
阅读 9
收藏 0

Writing tests might not have been the most enjoyable thing for you in the past but we for sure hope that after reading this article, you'll be able to increase the test coverage.

Today we're talking about snapshot tests using Jest. They're easy to write, they're fast, and most importantly, we'll for sure know if something is right if we use them correctly. These snapshots will warn us for Every change we make that affects the rendering: whether we're doing something simple, or more advanced rendering that includes conditions or looping.

Configure Jest

First, you need to setup jest in the project. For that install few packages:

npm install --save-dev jest babel-jest babel-core regenerator-runtime babel-preset-es2015 babel-preset-react 

You don't need to install regenerator-runtime if you use npm 3 or 4 or Yarn.
You'll have to add  .babelrc file in project root next:

{
  "presets": ["env", "es2015", "react"]
}

Also, you need to install react-test-renderer package. This package is isused to render react components to pure javascript objects.

npm i react-test-renderer --save

If you need some specific configuration for your tests, you can  configure jest using package.json file .

You're now ready to write your first snapshot test!

Writing snapshot tests

When writing snapshot tests using jest, you should basically just follow the next template:

import renderer from 'react-test-renderer';
import Component from '../Component.react';

it('renders correctly', () => {
  const tree = renderer.create(
    <Component 
        prop={propValue}
    />
  ).toJSON();
  expect(tree).toMatchSnapshot();
});

You use  react-test-renderer to create a component with butting  props , transform it to JSON and then check if it matches a snapshot. Easy, right?

Here's a more concrete example - let's say we have a dummy component called called Input, for which we want to write a snapshot test:

function Input({ id, placeholder, label, onChange, value }) {
    return (
        <div>
            <label htmlFor={id} >
                { label }
            </label>
            <input
                id={id}
                placeholder={placeholder}
                onChange={onChange}
                value={value}
            />
        </div>
    )
}

For our Input component, it can look something like this:

import renderer from 'react-test-renderer';
import Input from '../Input.react';

it('renders correctly', () => {
  const tree = renderer.create(
    <Input 
        id={'id'}
        label={'label'}
        placeholder={'Placeholder'}
        onChange={() => {}}
        value={''}
    />
  ).toJSON();
  expect(tree).toMatchSnapshot();
});

Running tests

To run the test, you just need to type type jest command in terminal. Output snapshot file will be created, and when running the test next time, jest will compare that output snapshot file to our updated component.

If you make some changes to a component that affects it's rendering, ( for example add a new item to the  list to be mapped ), the test will fail because the new object will be different from previous one. If changes were intended, you can at The Snapshot a using the Command Update command jest --updateSnapshot.

Keep in mind that all of these output snapshot files should be committed alongside the modules they are covering and their tests, as they are part of the test.

Of course, while our snapshot tests cover things like if  conditional rendering  is working properly, they don't test whether clicking on that link will properly redirect to another page. You will still need to write tests that check if the functionality works as expected, But those we'll be covering in some future article.

Thank you for your time reading!

Originally published on Kolosek Blog

© 著作权归作者所有

Kolosek
粉丝 0
博文 29
码字总数 20461
作品 0
塞尔维亚
CEO
私信 提问
开始测试React Native App(上篇)

前期技术储备 前言 我是测试小白,小小白,小小小白,最近想在成了一定规模的项目中引入测试,于是找了许些资料学习,现在已经在项目中成功引入。于是想在思路明朗和记忆深刻的时候总结下学习...

lyxia_iOS
2018/09/26
0
0
使用 enzyme + jest 测试 React 组件

最简单的测试 jest 是 Facebook 推出的测试工具,enzyme 是airbnb 推出的 React 测试类库,使用两者可以很好地测试 React 组件。 首先安装对应的依赖: 其中 是自动使用 babel 编译文件。 安...

_忽如寄
09/09
0
0
Jest 18.1.0 发布,JavaScript 单元测试工具

Jest 18.1.0 发布了,Jest 是 Facebook 开源的无痛 JavaScript 测试工具。Jest 默认使用 Jasmine assertions,模块化,可扩展、可配置。Jest 也可以捕获 React 或其他可序列化值的快照,以便...

王练
2016/12/31
744
0
wengcd/react-start-kit-flux-demo

React Starter Kit — "isomorphic" web app boilerplate React Starter Kit is an opinionated boilerplate for web development built on top of Facebook's React library, Node.js / Exp......

wengcd
2015/10/11
0
0
How to create-react-app with Docker

How to create-react-app with Docker Peterbe.com2017-11-171 阅读 ReactappdockerCREATE Why would you want to use Docker to do React app work? Isn't Docker for server-side stuff l......

Peterbe.com
2017/11/17
0
0

没有更多内容

加载失败,请刷新页面

加载更多

聊聊nacos config的deleteConfig

序 本文主要研究一下nacos config的deleteConfig ConfigController nacos-1.1.3/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java @Controller@Re......

go4it
昨天
4
0
面试:原来Redis的五种数据类型底层结构是这样的

关注我,可以获取最新知识、经典面试题以及微服务技术分享   在Redis中会涉及很多数据结构,比如SDS,双向链表、字典、压缩列表、整数集合等等。Redis会基于这些数据结构自定义一个对象系统...

ccww_
昨天
5
0
java发送html模板的高逼格邮件

最近做了一个监测k8s服务pod水平伸缩发送邮件的功能(当pod的cpu/内存达到指定阈值后会水平扩展出多个pod、或者指定时间内pod数应扩展到指定数量),一开始写了个格式很low的邮件,像下面这样...

码农实战
昨天
10
0
php-fpm配置文件详解/MariaDB密码重置、慢查询日志

来源:https://blog.csdn.net/Powerful_Fy php-fpm主配置文件路径:/usr/local/php-fpm/etc/php-fpm.conf #位于安装php安装目录下的etc/目录中,该文件中最后一行将配置文件指向:include=/...

asnfuy
昨天
10
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部