react-app 编写测试

jest Enzyme 文档 为什么要写测试

单元测试(unit testing)指的是以软件的单元(unit)为单位,对软件进行测试。单元可以是一个函数,也可以是一个模块或组件。它的基本特征就是,只要输入不变,必定返回同样的输出。

单元测试的步骤如下

准备所有的测试条件
    it('test a')
    it('test b')
调用(触发)所要测试的函数
    it('test a', ()=>{/*expect*/})
    it('test b', ()=>{/*expect*/})
验证运行结果是否正确
    npm t
还原被修改的记录

开发模式

TDD

先写好测试,然后再根据测试完成开发

BDD

针对行为写测试,软件应该怎样运行。

安装环境

yarn create react-app my-app
yarn run eject
yarn
yarn add enzyme enzyme-adapter-react-16 --dev

npm t 启动测试

浅层渲染 api

import React, { Component, Fragment } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  state = {
    v: 'welcome to react test.'
  }
  render() {
    const { v } = this.state;
    return <Fragment>
      <h1>{v}</h1>
      <button onClick={this.handleChangeV}>add</button>
    </Fragment>
  }

  handleChangeV = e => {
    this.setState({
      v: 'ok'
    })
  }
}

export default App;
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import Enzyme, {shallow} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({adapter: new Adapter()})
const l = console.log
describe('<App /> 组件测试', () => { // 测试套件
  let app;

  beforeAll(() => {
    app = shallow(< App />)
  })

  it('exists h1', () => { // 测试用例
    // 断言组件中存在 h1元素
    expect(app.exists('h1')).toBe(true) // 断言
  });

  it('only one h1', () => {
    // 断言只存在一个 h1袁元素
    expect(app.find('h1').length).toBe(1)
  })

  it('check h1 content', () => {
    expect(app.find('h1').html()).toContain('welcome to react test.')
  })

  it('click change', () => {
     app.find('button').simulate('click') // 模拟点击事件
    expect(app.find('h1').html()).toContain('ok')
    // expect(app.find('h1').html()).toContain('hello') Error

  })
})