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. Java反射异常处理之InvocationTargetException

    java.lang.reflect.InvocationTargetException处理办法可能是没有引commons-lang3-3.x.jar包

  2. codeforces 710C Magic Odd Square(构造或者n阶幻方)

    Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both ma ...

  3. MVC页面常用方法

    转自:https://www.cnblogs.com/baisoft/p/5839319.html @RenderBody 在Razor引擎中没有了“母版页”,取而代之的是叫做“布局”的页面(_Lay ...

  4. VNC CentOS Linux下VNC Server远程桌面配置详解

    VNC概述 VNC (Virtual Network Console)是虚拟网络控制台的缩写.VNC 是一款优秀的远程控制工具软件,由著名的 AT&T 的欧洲研究实验室开发的.VNC 是在基于 ...

  5. ImportError: cannot import name pxssh

    Traceback (most recent call last): File "/root/Desktop/JuniperBackdoor-master/JuniperBackdoor.p ...

  6. TI Code Composer Studio MSP430系列驱动源代码

    一.参考TI官网驱动源代码 安装打开Code Composer Studio,如下图所示,最近在调试MSP430G2533的AD,需要参考官网的底层驱动配置. 从Code Composer Studi ...

  7. oracle 01578

    http://blog.itpub.net/7728585/viewspace-670597/ http://www.2cto.com/database/201208/149056.html http ...

  8. HDU 3714 Error Curves

    Error Curves 思路:这个题的思路和上一个题的思路一样,但是这个题目卡精度,要在计算时,卡到1e-9. #include<cstdio> #include<cstring& ...

  9. openssl之EVP系列之5---EVP_Encrypt系列函数具体解释(二)

    openssl之EVP系列之5---EVP_Encrypt系列函数详细解释(二)    ---依据openssl doc/crypto/EVP_EncryptInit.pod和doc/ssleay.t ...

  10. Dynamics CRM2013/2015 插件注冊工具登录后无法显示assembly列表问题的解决的方法

    自微软从2013版本号推出新的插件注冊器后,随着UI的重大更新后,问题也多了非常多.前面已有博客提到注冊assembly时看不到注冊button(http://blog.csdn.net/vic022 ...