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

Toggle component:

  1. // see this live: https://codesandbox.io/s/GvWpGjKQ
  2. import React, {Component} from 'react'
  3. import PropTypes from 'prop-types'
  4. import glamorous from 'glamorous'
  5. import {darken} from 'polished'
  6.  
  7. // imagine this is in a "components" file
  8. const primaryColor = '#337ab7'
  9. const toggledOnStyles = {
  10. backgroundColor: darken(0.15, primaryColor),
  11. borderColor: darken(0.25, primaryColor),
  12. '&:hover,&:active,&:focus': {
  13. backgroundColor: darken(0.2, primaryColor),
  14. borderColor: darken(0.3, primaryColor),
  15. },
  16. }
  17. const toggledOffStyles = {
  18. backgroundColor: primaryColor,
  19. borderColor: darken(0.1, primaryColor),
  20. '&:hover,&:active,&:focus': {
  21. backgroundColor: darken(0.1, primaryColor),
  22. borderColor: darken(0.2, primaryColor),
  23. },
  24. }
  25. const ToggleButton = glamorous.button(
  26. {
  27. display: 'inline-block',
  28. padding: '6px 12px',
  29. marginBottom: '0',
  30. fontSize: '14px',
  31. fontWeight: '400',
  32. lineHeight: '1.4',
  33. textAlign: 'center',
  34. cursor: 'pointer',
  35. borderRadius: '4px',
  36. color: '#fff',
  37. },
  38. props => (props.on ? toggledOnStyles : toggledOffStyles),
  39. )
  40.  
  41. class Toggle extends Component {
  42. constructor(props, ...rest) {
  43. super(props, ...rest)
  44. this.state = {
  45. toggledOn: props.initialToggledOn || false,
  46. }
  47. }
  48.  
  49. handleToggleClick = () => {
  50. const toggledOn = !this.state.toggledOn
  51. this.props.onToggle(toggledOn)
  52. this.setState({toggledOn})
  53. }
  54.  
  55. render() {
  56. const {children} = this.props
  57. const {toggledOn} = this.state
  58. return (
  59. <ToggleButton
  60. on={toggledOn}
  61. onClick={this.handleToggleClick}
  62. data-test="button"
  63. >
  64. {children}
  65. </ToggleButton>
  66. )
  67. }
  68. }
  69.  
  70. Toggle.propTypes = {
  71. initialToggledOn: PropTypes.bool,
  72. onToggle: PropTypes.func.isRequired,
  73. children: PropTypes.any.isRequired,
  74. }
  75.  
  76. export default Toggle

Test:

  1. import React from 'react'
  2. import {render, mount} from 'enzyme'
  3. import Toggle from '../toggle'
  4.  
  5. test('component render with default state', () => {
  6. const wrapper = renderToggle();
  7. expect(wrapper).toMatchSnapshotWithGlamor();
  8. })
  9.  
  10. test('when button is clicked, the style of button should change', () => {
  11. const onToggle = jest.fn() // jest mock function
  12. const wrapper = mountToggle({
  13. onToggle
  14. })
  15. // It is recommended that for the element we need to test
  16. // we can add 'data-test' attr, so that we can reference
  17. // the element inside testing
  18. const button = wrapper.find('[data-test="button"]')
  19. // we can verify the style changes inside snapshots
  20. expect(wrapper).toMatchSnapshotWithGlamor('1. Before toggle')
  21. button.simulate('click')
  22. expect(wrapper).toMatchSnapshotWithGlamor('2. After toggle')
  23. })
  24.  
  25. test('onToggle function should be called when the button is clicked', () => {
  26. const onToggle = jest.fn() // jest mock function
  27. const wrapper = mountToggle({
  28. onToggle
  29. })
  30. // It is recommended that for the element we need to test
  31. // we can add 'data-test' attr, so that we can reference
  32. // the element inside testing
  33. const button = wrapper.find('[data-test="button"]')
  34. button.simulate('click')
  35. expect(onToggle).toHaveBeenCalledTimes(1)
  36. expect(onToggle).toHaveBeenCalledWith(true)
  37. })
  38.  
  39. /**
  40. * The difference between mount and render function is that
  41. * 1. render is faster, because after rendered, it output string,
  42. * so there is no lifecycle hooks bind with it.
  43. * 2. mount, on the other hand, will bind lifecycle hooks and events,
  44. * the output is actual DOM element
  45. * */
  46.  
  47. function mountToggle(props = {}) {
  48. const propToUse = Object.assign(
  49. {},
  50. {
  51. onToggle() {
  52. },
  53. children: 'I am a child'
  54. },
  55. props
  56. )
  57.  
  58. return mount(<Toggle {...propToUse} />)
  59. }
  60.  
  61. function renderToggle(props = {}) {
  62. const propToUse = Object.assign(
  63. {},
  64. {
  65. onToggle() {
  66. },
  67. children: 'I am a child'
  68. },
  69. props
  70. )
  71.  
  72. return render(<Toggle {...propToUse} />)
  73. }

[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. STL使用————SET&MULTISET

    SET函数的基本用法 by hhl 使用set的好处 1. 当增加元素后,集合会自动删重并从小到大排列(时间比快排还快)2. 相当于一棵伸展树(能快速求出后继) 使用基础 #include<se ...

  2. Android 仿QQ首页的消息和电话的切换,首页的头部(完全用布局控制)

    Android 仿QQ首页的消息和电话的切换,首页的头部(完全用布局控制) 首先贴上七个控制布局代码 1.title_text_sel.xml 字体颜色的切换 放到color文件夹下面 <?xm ...

  3. 为什么linux驱动中变量或者函数都用static修饰?(知乎问题)

    static定义的全局变量 或函数也只能作用于当前的文件. 世界硬件厂商太多,定义static为了防止变量或 函数 重名,定义成static, 就算不同硬件驱动中的 变更 或函数重名了也没关系 .

  4. Safe and efficient allocation of memory

    Aspects of the present invention are directed at centrally managing the allocation of memory to exec ...

  5. 洛谷 P1994 有机物燃烧

    P1994 有机物燃烧 题目背景 本来准备弄难点的,还是算了吧 题目描述 输入一种有机物,输出与氧气反应化学方程式中CO2和H2O的系数 输入输出格式 输入格式: 一行,一个字符串,表示有机物 输出格 ...

  6. 比MD5 和HMAC还要安全的加密 - MD5 加时间戳

    //1.给一个字符串进行MD5加密 NSString *passKey = @"myapp"; passKey = [passKey md5String]; //2.对第一步中得到 ...

  7. h5播放音乐

    h5音频播放,里面參数能够查看http://www.w3school.com.cn/html5/html_5_audio.asp <audio controls="controls&q ...

  8. 41.Node.js使用cnpm

    转自:http://www.runoob.com/nodejs/nodejs-tutorial.html npm是Node.js中维护第三方库.模块的工具,但是国外的速度很悲剧,这里有一个中国的源cn ...

  9. vue (v-if show 问题)

    vue中的显示和隐藏有两种方式 1.v-if   ( 相当于动态创建的标签,在html 结构中,是不存在的. ) 2. v-show(控制的是 html 的css display:none  属性.结 ...

  10. CDQZ 0003:jubeeeeeat

    0003:jubeeeeeat 查看 提交 统计 提问 总时间限制:  1000ms 内存限制:  256000kB 描述 众所周知,LZF很喜欢打一个叫Jubeat的游戏.这是个音乐游戏,游戏界面是 ...