[React & Testing] Simulate Event testing
2024-08-31 19:06:36
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} />)
}
最新文章
- js自定义弹出框
- (44) odoo中的WebService
- php生成html文件的多种方法介绍
- HAXM cannot be installed nutil TV-x is enabled
- JAVA中单例模式的几种实现方式
- eclipse设置总结
- ByteArrayInputStream 和 ByteArrayOutputStream
- hdu 4107当卡段树
- 深入浅出了解OCR识别票据原理
- (sqlite3.OperationalError) no such table: users [SQL: &#39;SELECT users.id AS users_id, users.email AS users_email, users.username AS users_username, users.role_id AS users_role_id, users.password_hash A
- select, poll, epoll的实现分析
- RACSignal的一些常用用法
- 用LED灯和按键来模拟工业自动化设备的运动控制
- C++头文件用<;>;还是“” 以及 要加.h还是不加 的问题
- [原创]GDB调试指南-断点设置
- linux操作系统中oracle数据库的密码过期问题解决
- .NET基于分页控件实现真分页功能
- CF 1093 G. Multidimensional Queries
- Objective-C:ARC自动释放对象内存
- 新建用户组、用户、用户密码、删除用户组、用户(适合CentOS、Ubuntu系统)
热门文章
- 用iptables抗御SYN Flood攻击
- (转载)http协议的Request Payload 和 Form Data 的区别
- 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛 (B,F,L,M)
- 我比xx强在哪里?弱在哪里?
- 打印机共享 : 客户端 连接服务器打印机时提示";无法连接到打印机“
- 学习《SQL必知必会(第4版)》中文PDF+英文PDF+代码++福达BenForta(作者)
- Yeslab 华为安全HCIE-第五门-防火墙攻击防范技术
- 今日SGU 5.17
- jQuery获取区间随机数
- cz.msebera.android.httpclient.conn.ConnectTimeoutException: Connect to /192.168.23.1:8080 timed out(Android访问后台一直说链接超时)