React 单元测试教程(1)

#1

使用技术

概要

  1. 测试函数(不涉及 React)
  2. 测试组件(不包含 state)
  3. 测试组件(包含 state)

1. 函数(不涉及 React)

两步

  1. 调用被测试函数
  2. 设置期待结果
import { toDate } from './dateUtil'

describe('test dateUtil', () => {
  it('test String to Date', () => {
    expect(toDate('2018-05-10 10:33:27', 'YYYY-MM-DDTHH:mm:ss')).toEqual(
      new Date('2018-05-10 10:33:27'),
    )
  })
})

2. 组件(不包含 state)

两步

  1. 渲染被测试组件
  2. 设置期待组件属性
import { shallow } from 'enzyme'

describe('<TagView />', () => {
  it('prop.data can be underfined', () => {
    const wrapper = shallow(<TagView />)
    expect(wrapper.prop.data).toBe(undefined)
  })
})

3. 组件(包含 state)

三步

  1. 渲染被测试组件
  2. 模拟某个可以改变 state 的事件
  3. 设置期待 state
import { shallow } from 'enzyme'

it('click "unliked" button, should be liked', () => {
  const wrapper = shallow(<LikeButton />)
  wrapper.find('.common').simulate('click')
  expect(wrapper.state('liked')).toEqual(true)
})

// 模拟鼠标
// wrapper.find('.common').simulate('mouseenter')
// 模拟输入
// wrapper.find(Input).simulate('change', {target: {value: 'hello test.'}})