React Jest UI测试

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37068028/article/details/83625354

组件

// 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

测试结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_37068028/article/details/83625354