[React & Testing] Snapshot testings

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)

 

posted @   Zhentiw  阅读(416)  评论(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工具
历史上的今天:
2016-09-20 [Angular 2] Angular 2 Smart Components vs Presentation Components
2016-09-20 [Angular 2] Share a Service Across Angular 2 Components and Modules
2016-09-20 [Angular 2] How To Debug An Angular 2 Application - Debugging via Augury or the Console
点击右上角即可分享
微信分享提示