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

Toggle component:

// 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

Test:

import React from 'react'
import {render, mount} from 'enzyme'
import Toggle from '../toggle' test('component render with default state', () => {
const wrapper = renderToggle();
expect(wrapper).toMatchSnapshotWithGlamor();
}) test('when button is clicked, the style of button should change', () => {
const onToggle = jest.fn() // jest mock function
const wrapper = mountToggle({
onToggle
})
// It is recommended that for the element we need to test
// we can add 'data-test' attr, so that we can reference
// the element inside testing
const button = wrapper.find('[data-test="button"]')
// we can verify the style changes inside snapshots
expect(wrapper).toMatchSnapshotWithGlamor('1. Before toggle')
button.simulate('click')
expect(wrapper).toMatchSnapshotWithGlamor('2. After toggle')
}) test('onToggle function should be called when the button is clicked', () => {
const onToggle = jest.fn() // jest mock function
const wrapper = mountToggle({
onToggle
})
// It is recommended that for the element we need to test
// we can add 'data-test' attr, so that we can reference
// the element inside testing
const button = wrapper.find('[data-test="button"]')
button.simulate('click')
expect(onToggle).toHaveBeenCalledTimes(1)
expect(onToggle).toHaveBeenCalledWith(true)
}) /**
* The difference between mount and render function is that
* 1. render is faster, because after rendered, it output string,
* so there is no lifecycle hooks bind with it.
* 2. mount, on the other hand, will bind lifecycle hooks and events,
* the output is actual DOM element
* */ function mountToggle(props = {}) {
const propToUse = Object.assign(
{},
{
onToggle() {
},
children: 'I am a child'
},
props
) return mount(<Toggle {...propToUse} />)
} function renderToggle(props = {}) {
const propToUse = Object.assign(
{},
{
onToggle() {
},
children: 'I am a child'
},
props
) return render(<Toggle {...propToUse} />)
}

[React & Testing] Simulate Event testing的更多相关文章

  1. Unit Testing, Integration Testing and Functional Testing

    转载自:https://codeutopia.net/blog/2015/04/11/what-are-unit-testing-integration-testing-and-functional- ...

  2. Difference Between Performance Testing, Load Testing and Stress Testing

    http://www.softwaretestinghelp.com/what-is-performance-testing-load-testing-stress-testing/ Differen ...

  3. Go testing 库 testing.T 和 testing.B 简介

    testing.T 判定失败接口 Fail 失败继续 FailNow 失败终止 打印信息接口 Log 数据流 (cout 类似) Logf format (printf 类似) SkipNow 跳过当 ...

  4. [AngularJS Unit tesint] Testing keyboard event

    HTML: <div ng-focus="vm.onFocus(month)", aria-focus="{{vm.focus == month}}", ...

  5. [Unit Testing] AngularJS Unit Testing - Karma

    Install Karam: npm install -g karma npm install -g karma-cli Init Karam: karma init First test: 1. A ...

  6. Penetration Testing、Security Testing、Automation Testing

    相关学习资料 http://www.cnblogs.com/LittleHann/p/3823513.html http://www.cnblogs.com/LittleHann/p/3828927. ...

  7. 测试理论--branch testing and boundary testing

    1 branch testing 分支测试 测试代码的所有分支 2 boundary testing 测试 程序的限制条件

  8. [Unit Testing] Fundamentals of Testing in Javascript

    In this lesson, we’ll get the most fundamental understanding of what an automated test is in JavaScr ...

  9. [Angular Unit Testing] Debug unit testing -- component rendering

    If sometime you want to log out the comonent html to see whether the html render correctly, you can ...

随机推荐

  1. .net core的安装

    安装完成后的路径在C:\Program Files\dotnet https://github.com/dotnet/cli/issues/390 ===2017年06月29日=== 安装成功之后,配 ...

  2. Ubuntu 13.04/CentOS 6.4 下C++开发时的相关设置

    Ubuntu 13.04/CentOS 6.4 下C++开发时的相关设置 一.基本设置 首先,为了可以使我们的c++ 可以找到 iostream类,std标准库,我们需要在C/C++ General- ...

  3. ajax --- Ajax跨域请求保证同一个session的问题

    我们知道,根据浏览器的保护规则,跨域的时候我们创建的sessionId是不会被浏览器保存下来的,这样,当我们在进行跨域访问的时候,我们的sessionId就不会被保存下来,也就是说,每一次的请求,服务 ...

  4. POJ 1610 Count the Colors

    Count the Colors Time Limit: 2 Seconds      Memory Limit: 65536 KB Painting some colored segments on ...

  5. Flex之登录界面

    制作登录框界面 环境搭建:MyEclipse 6.5+Flex Builder 3 Plug-in <?xml version="1.0" encoding="ut ...

  6. Django transaction 误用之后遇到的一个问题与解决方法

    今天在调试项目开发好的一个模块的时候,发现了一个很诡异的现象,最后追踪发现是因为在项目中事务处理有误所致.这个问题坑了我好一会,所以记录一下,以免再踩坑.下面开始详述. 我们都知道 Django 框架 ...

  7. crawlspider抽屉爬取实例+分布

    创建项目 scrapy startproject choutiPro 创建爬虫文件  scrapy genspider -t crawl chouti www.xxx.com 进入pycharm 培训 ...

  8. Python——Pygame实现生命游戏(game of life)

    模块:pygame import pygame,sys,time,random from pygame.locals import * """Color"&qu ...

  9. CSUOJ 1603 Scheduling the final examination

    1603: Scheduling the final examination Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 49  Solved: 1 ...

  10. EditPlus,UltraEdit等编辑器列选择的方法

    在使用富文本编辑器的时候,通常模式是行选择状态,由于今天想使用EditPlus列选择状态, 于是通过在网上收集的资料,总结出相关富文本编辑器的列选择的方法. EditPlus  1)菜单:编辑 -&g ...