1. 程式人生 > >React Jest UI測試

React Jest UI測試

元件

// demo.js
import React, { PureComponent } from 'react'

class Demo extends PureComponent {
  static defaultProps = {
    title: 'This is a demo',
    value: 0
  }

  constructor (props) {
    super(props)

    const {title, value} = props

    this.state = {
      title,
      value
    }
  }

  add = () => {
    this.setState({
      value: this.state.value +1
    })
  }

  change = ev => {
    this.setState({
      value: ev.target.value
    })
  }

  componentWillReceiveProps (nextProps) {
    this.setState({
      title: nextProps.title
    })
  }

  render() {
    return (
      <div className="container">
        <h1>{this.state.title}</h1>
        <div className="counter">{this.state.value}</div>
        <input value={this.state.value} onChange={this.change} />
        <button onClick={this.add}>value ++</button>
      </div>
    )
  }

}

export default Demo

測試程式碼

// demo.test.js
import React from 'react';
import Enzyme, { mount } from 'enzyme'
import sinon from 'sinon'
import Adapter from 'enzyme-adapter-react-16';
import Demo from '../src/demo'

Enzyme.configure({ adapter: new Adapter() });

// UI測試
describe('UI test #demo', () => {
  it('should have title', () => {
    const wrapper = mount(<Demo />)
    const title = wrapper.find('h1')
    expect(title).toHaveLength(1)
    expect(title.text()).toBe('This is a demo')
  })

  // 點選測試
  it('should add 1 when click button', () => {
    const wrapper = mount(<Demo />)
    const counter = wrapper.find('.counter')
    const v1 = parseInt(counter.text())
    wrapper.find('button').simulate('click')
    const v2 = parseInt(counter.text())
    expect(v2).toBe(v1 + 1)
  })

  // 輸入測試
  it('should change when input number', () => {
    const wrapper = mount(<Demo />)
    const counter = wrapper.find('.counter')
    wrapper.find('input').simulate('change', {
      target: {
        value: '5'
      }
    })
    expect(counter.text()).toBe('5')
  })

  // props傳值和生命週期測試
  it('should change when props change', () => {
    const wrapper = mount(<Demo title="Demo" value={5} />)
    sinon.spy(Demo.prototype, 'componentWillReceiveProps')
    const title = wrapper.find('h1')
    wrapper.setProps({
      title: 'Demo2'
    })
    expect(title.text()).toBe('Demo2')

    const callCount = Demo.prototype.componentWillReceiveProps.callCount
    expect(callCount).toBe(1)
  })
})
// .babelrc
{
  "presets": ["env", "react"],
  "plugins": [
    "transform-class-properties"
  ]
}

執行命令

jest test/demo.test.js --coverage

測試結果
在這裡插入圖片描述