For example we have a React comonent: -- A toggle button, we want to test. When it si toggle on, the color is a little bit darken than it's not.

// see this live: https://codesandbox.io/s/GvWpGjKQ
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import glamorous from 'glamorous'
import {darken} from 'polished' // imagine this is in a "components" file
const primaryColor = '#337ab7'
const toggledOnStyles = {
backgroundColor: darken(0.15, primaryColor),
borderColor: darken(0.25, primaryColor),
'&:hover,&:active,&:focus': {
backgroundColor: darken(0.2, primaryColor),
borderColor: darken(0.3, primaryColor),
},
}
const toggledOffStyles = {
backgroundColor: primaryColor,
borderColor: darken(0.1, primaryColor),
'&:hover,&:active,&:focus': {
backgroundColor: darken(0.1, primaryColor),
borderColor: darken(0.2, primaryColor),
},
}
const ToggleButton = glamorous.button(
{
display: 'inline-block',
padding: '6px 12px',
marginBottom: '0',
fontSize: '14px',
fontWeight: '400',
lineHeight: '1.4',
textAlign: 'center',
cursor: 'pointer',
borderRadius: '4px',
color: '#fff',
},
props => (props.on ? toggledOnStyles : toggledOffStyles),
) class Toggle extends Component {
constructor(props, ...rest) {
super(props, ...rest)
this.state = {
toggledOn: props.initialToggledOn || false,
}
} handleToggleClick = () => {
const toggledOn = !this.state.toggledOn
this.props.onToggle(toggledOn)
this.setState({toggledOn})
} render() {
const {children} = this.props
const {toggledOn} = this.state
return (
<ToggleButton
on={toggledOn}
onClick={this.handleToggleClick}
data-test="button"
>
{children}
</ToggleButton>
)
}
} Toggle.propTypes = {
initialToggledOn: PropTypes.bool,
onToggle: PropTypes.func.isRequired,
children: PropTypes.any.isRequired,
} export default Toggle

Testing:

import React from 'react'
import {render} from 'enzyme'
import Toggle from '../toggle' test('component render with default state', () => {
const wrapper = render(<Toggle
onToggle={() => {}}>I am child</Toggle>)
expect(wrapper).toMatchSnapshotWithGlamor();
})

If anything changes in the component, such as style changes, snapshot will catch the changes and ask whether should update current snapshot to match the change or it might be the bug, you need to update the code. It save our time which previously we did as a manual thing, now its automaticlly.

To make things work together, need to change some settings:

jest.config.js:

{
"setupFiles": [
"<rootDir>/config/jest/setup-tests.js"
],
"setupTestFrameworkScriptFile": "<rootDir>/config/jest/setup-framework.js",
"testEnvironment": "jest-environment-jsdom",
"roots": [
"demo/unit"
],
"testPathIgnorePatterns": [
"/helpers/"
],
"snapshotSerializers": [
"enzyme-to-json/serializer"
]
}

setup-tests.js:

// here we set up a fake localStorage because jsdom doesn't support it
// https://github.com/tmpvar/jsdom/issues/1137
const inMemoryLocalStorage = {}
window.localStorage = {
setItem(key, val) {
inMemoryLocalStorage[key] = val
},
getItem(key) {
return inMemoryLocalStorage[key]
},
removeItem(key) {
delete inMemoryLocalStorage[key]
},
}

set-framework.js:

import {matcher, serializer} from 'jest-glamor-react'

expect.extend(matcher)
expect.addSnapshotSerializer(serializer)

[React & Testing] Snapshot testings的更多相关文章

  1. 如何使用TDD和React Testing Library构建健壮的React应用程序

    如何使用TDD和React Testing Library构建健壮的React应用程序 当我开始学习React时,我努力的一件事就是以一种既有用又直观的方式来测试我的web应用程序. 每次我想测试它时 ...

  2. React Testing All in One

    React Testing All in One React 测试 https://reactjs.org/docs/testing.html jest 26.4 https://jestjs.io/ ...

  3. [React Testing] Children with Shallow Rendering

    When testing React components, we often want to make sure the rendered output of the component match ...

  4. [React Testing] JSX error diffs -- expect-jsx library

    When writing React component tests, it can be hard to decipher the error diffs of broken tests, sinc ...

  5. [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- ...

  6. [React Testing] Setting up dependencies && Running tests

    To write tests for our React code, we need to first install some libraries for running tests and wri ...

  7. [React & Testing] Simulate Event testing

    Here we want to test a toggle button component, when the button was click, state should change, styl ...

  8. [React Testing] The Redux Store - Multiple Actions

    When using Redux, we can test that our application state changes are working by testing that dispatc ...

  9. [React Testing] Conditional className with Shallow Rendering

    Often our components have output that shows differently depending on the props it is given; in this ...

随机推荐

  1. php中对象转数组有哪些方法(总结测试)

    php中对象转数组有哪些方法(总结测试) 一.总结 一句话总结:json_decode(json_encode($array),true)和array强制转换(或带递归) 1.array方式强制转换对 ...

  2. ADO.Net数据库帮助类

    public interface IDBHelper { /// <summary> /// 执行sql语句 /// </summary> /// <param name ...

  3. PowerDesigner删除外键关系,而不删除外键列[转] 及编码格式

    PowerDesigner删除外键关系,而不删除外键列[转]  数据库 database  -> generate database ->format 设置为utf-8 PowerDesi ...

  4. excel操作小技巧

    excel拼接sql语句时,时间格式问题 问题:若直接插入时间的单元格 :="insert into t_entity_car (create_time,name,age) value (' ...

  5. Codeforces Round #206 (Div. 2) 部分题解

    传送门:http://codeforces.com/contest/355 A:水题,特判0 int k,d; int main(){ //FIN; while(cin>>k>> ...

  6. caioj 1063 动态规划入门(一维一边推1:美元和马克)

    这道题一开始我是这么想的 最后的答案肯定是某次的马克换回来的,但这个该怎么确定?? 实际上应该把范围缩小,只看最后一次和倒数第二次之间有什么联系. 可以发现,只有两种可能,最后一天换或者不换.换的话就 ...

  7. Android中Service的一个Demo例子

    Android中Service的一个Demo例子  Service组件是Android系统重要的一部分,网上看了代码,很简单,但要想熟练使用还是需要Coding.  本文,主要贴代码,不对Servic ...

  8. HDU1788 Chinese remainder theorem again【中国剩余定理】

    题目链接: pid=1788">http://acm.hdu.edu.cn/showproblem.php?pid=1788 题目大意: 题眼下边的描写叙述是多余的... 一个正整N除 ...

  9. JAVA基础实例(二)

    1.做一个饲养员给动物喂食物的样例体现JAVA中的面向对象思想,接口(抽象类)的用处 package com.softeem.demo; /** *@authorleno *动物的接口 */ inte ...

  10. 请求头header里的contentType为application/json和capplition/x-www-form-urlencoded

    application/x-www-form-urlencoded 最常见的 POST 提交数据的方式了.浏览器的原生 <form> 表单,如果不设置 enctype 属性,那么最终就会以 ...