React 单元测试教程(2)

#1

使用技术

概要

  1. 测试 props
  2. 测试 state
  3. 测试函数调用

1. 测试 props

import React from 'react'
import { shallow } from 'enzyme'

it('disabled, cursor should be "not-allowed"', () => {
  const wrapper = shallow(<LikeButton disabled />)
  expect(wrapper.prrops().style).toHaveProperty('cursor', 'not-allowed')
})

2. 测试 state

import React from 'react'
import { shallow } from 'enzyme'

it('mouse enter, hover should be true', () => {
  const wrapper = shallow(<LikeButton />)
  wrapper.find('.common').simulate('mouseenter')

  // == wrapper.state('hover')
  expect(wrapper.state().hover).toEqual(true)
})

3. 测试函数调用

import React from 'react'
import { shallow } from 'enzyme'

it('TextArea onChange', () => {
  // mock
  const onchange = jest.fn()

  const wrapper = shallow(
    <SimpleText
      type="simple-text"
      value="This is a Simple Text."
      onChange={onchange}
    />
  )

  wrapper.find(TextArea).simulate('change', {
    target: { value: 'welcome test SimpleText part.' }
  })

  expect(onchange.mock.calls.length).toBe(1)
})
#2

Hi,博主,你好 可以请教你一些稍微复杂些的React测试吗

1 Like
#3

可以的,你说的复杂是指什么呢?