[React & Testing] Simulate Event testing
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的更多相关文章
- Unit Testing, Integration Testing and Functional Testing
转载自:https://codeutopia.net/blog/2015/04/11/what-are-unit-testing-integration-testing-and-functional- ...
- Difference Between Performance Testing, Load Testing and Stress Testing
http://www.softwaretestinghelp.com/what-is-performance-testing-load-testing-stress-testing/ Differen ...
- Go testing 库 testing.T 和 testing.B 简介
testing.T 判定失败接口 Fail 失败继续 FailNow 失败终止 打印信息接口 Log 数据流 (cout 类似) Logf format (printf 类似) SkipNow 跳过当 ...
- [AngularJS Unit tesint] Testing keyboard event
HTML: <div ng-focus="vm.onFocus(month)", aria-focus="{{vm.focus == month}}", ...
- [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 ...
- Penetration Testing、Security Testing、Automation Testing
相关学习资料 http://www.cnblogs.com/LittleHann/p/3823513.html http://www.cnblogs.com/LittleHann/p/3828927. ...
- 测试理论--branch testing and boundary testing
1 branch testing 分支测试 测试代码的所有分支 2 boundary testing 测试 程序的限制条件
- [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 ...
- [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 ...
随机推荐
- Android View体系(九)自定义View
相关文章 Android View体系(一)视图坐标系 Android View体系(二)实现View滑动的六种方法 Android View体系(三)属性动画 Android View体系(四)从源 ...
- AngularJS初接触
todo.json [ { "action": "Buy Flowers", "done": false }, { "action ...
- Spring MVC 待学习---新特性
Spring3.1新特性 一.Spring2.5之前,我们都是通过实现Controller接口或其实现来定义我们的处理器类. 二.Spring2.5引入注解式处理器支持,通过@Controller ...
- BZOJ 1103 DFS序+线段树
思路: 先搞出来DFS序 进入这个点 +1 出这个点 -1 线段树维护前缀和 (因为还要修改) 搞定 修改的时候只修改底下节点就OK了 (边权–>点权 不多说) //By SiriusRen # ...
- js实现导出数据到excel
来自:http://www.imooc.com/article/13374 //html代码<!DOCTYPE HTML> <html> <head> <ti ...
- sed的一些tricks
1.sed -f xx.sed input_file 可以将一系列操作放在一个xx.sed脚本里执行 ``` #!/bin/sed -f ``` 2.在匹配字符串后面或行尾添加内容 在text后面添加 ...
- 【剑指offer】Q25:二叉树中和为某一值的路径
说明:最烦的就是看别人的博客,题解里直接上代码,一行分析都没有.只是这个题... class BTNode(): def __init__(self, val = -1): self.val = va ...
- 【BUG】"main" prio=5 tid=1 RUNNABLE
载入超大效果图导致内存不足(GC/ANR) 06-30 11:42:56.624: D/dalvikvm(16264): GC_CONCURRENT freed 1982K, 7% free 4537 ...
- 參考mudo logging写的win下logging
#pragma once #include <boost/noncopyable.hpp> #include <boost/scoped_ptr.hpp> #include & ...
- 消灭星星的数组高效率算法(c++代码,控制台程序)
#include <iostream> using namespace std; #define ROW 12 #define COL 10 class Star { public: en ...