jest + enzyme测试react组件

时间:2020-01-09
本文章向大家介绍jest + enzyme测试react组件,主要包括jest + enzyme测试react组件使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1、demo结构

 

2、项目搭建

  创建项目:create-react-app jest_4

  package.json

{
  "name": "jest_4",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "3.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest --colors --coverage",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "@babel/core": "*",
    "@babel/plugin-proposal-class-properties": "*",
    "@babel/preset-env": "*",
    "@babel/preset-react": "*",
    "babel-jest": "*",
    "enzyme": "*",
    "enzyme-adapter-react-16": "*",
    "jest": "*"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

  .babelrc.js

module.exports = {
  presets: ['@babel/preset-env', '@babel/preset-react'],
  plugins: ['@babel/plugin-proposal-class-properties']
};

  index.js

import React from 'react'
import ReactDOM from 'react-dom'

import Home from './components/Home.jsx'

ReactDOM.render(<Home />, document.getElementById('root'))

  Home.jsx

import React from 'react'

export default class Home extends React.Component {
    static defaultProps = {
        title: 'jest + enzyme demo',
        value: 0
    }

    constructor(props) {
        super(props)
        const { title, value } = props
        this.state = {
            title,
            value
        }
    }

    componentWillReceiveProps(newProps) {
        const { title, value } = newProps
        this.setState({ title, value })
    }

    render() {
        const { title, value } = this.state
        return (
            <div>
                <h1>{title}</h1>
                <div className='show-value'>value = {value}</div>
                <input value={value} onChange={this.changeHandler} />
                <button onClick={this.add}>Value++</button>
            </div>
        )
    }

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

    changeHandler = e => {
        this.setState({
            value: e.target.value
        })
    }

}

 

  __tests__/Home-test.js

import React from 'react';
import Enzyme, {mount} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Home from '../src/components/Home.jsx';

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

describe('UI test #home', () => {
    it('shoule have title', () => {
        const wrapper = mount(<Home />)
        const title = wrapper.find('h1')
        expect(title).toHaveLength(1)
    })

    it('should add 1 when click button', () => {
        const wrapper = mount(<Home />)
        const showValue = wrapper.find('.show-value')
        const inputOldValue = parseInt(showValue.text())
        // 模拟button点击事件
        wrapper.find('button').simulate('click')
        const inputCurrentValue = parseInt(showValue.text())
        expect(inputCurrentValue).toBe(inputOldValue + 1)
    })

    it('should change to the input value when input a number', () => {
        const wrapper = mount(<Home />)
        const showValue = wrapper.find('.show-value')
        // 模拟监听input输入框的change事件
        wrapper.find('input').simulate('change', {
            target: {
                value: '5'
            }
        })
        expect(showValue.text()).toBe("value = 5")
    })

    it('should change when props change', () => {
        const wrapper = mount(<Home title="aaa"/>)
        const title = wrapper.find('h1')

        expect(title.text()).toBe('aaa')
        
        wrapper.setProps({
            title: 'bbb'
        })

        expect(title.text()).toBe('bbb')
    })

})

 

3、测试

  执行npm test

 

参考:

  1) Testing React Apps

  2) https://github.com/facebook/jest/tree/master/examples/enzyme

$flag 上一页 下一页