React+Redux单元测试一小时入门

一、工具介绍

  • karma:测试过程管理工具。可以监控文件变化自动执行单元测试,可以缓存测试结果,可以console.log显示测试过程中的变量

  • mocha:测试框架。提供describe,it,beforeEach等函数管理你的 testcase,后面示例中会看到

  • chai:BDD(行为驱动开发)和TDD(测试驱动开发)双测试风格的断言库

  • enzyme:React测试工具,可以类似 jquery 风格的 api 操作react 节点

  • sinon: 提供 fake 数据, 替换函数调用功能

二、环境准备

工具安装就是 npm install,这里就不再详述,主要的配置项目在karma.conf.js中,可以参考这个模板项目 react-redux-starter-kit 。如果项目中用到全局变量,比如jquery,momentjs等,需要在测试环境中全局引入,否则报错,例如,在karma.conf中引入全局变量jQuery:

{
    files: [
    './node_modules/jquery/jquery.min.js',{
      pattern: `./tests/test-bundler.js`,watched: false,served: true,included: true
    }
  ]
}

在test-bundler.js中设置全局的变量,包括chai,sinon等:

/* tests/test-bundler.js */

import 'babel-polyfill'
import sinon from 'sinon'
import chai from 'chai'
import sinonChai from 'sinon-chai'
import chaiAsPromised from 'chai-as-promised'
import chaiEnzyme from 'chai-enzyme'

chai.use(sinonChai)
chai.use(chaiAsPromised)
chai.use(chaiEnzyme())

global.chai = chai
global.sinon = sinon
global.expect = chai.expect
global.should = chai.should()

...

三、简单的函数测试

先热身看看简单的函数如何单元测试:

/* helpers/validator.js */

export function checkUsername (name) {
  if (name.length === 0 || name.length > 15) {
    return '用户名必须为1-15个字'
  }
  return ''
}
/* tests/helpers/validator.spec.js */

import * as Validators from 'helpers/validator'

describe('helpers/validator',() => {
    describe('Function: checkUsername',() => {
        it('Should not return error while input foobar.',() => {
            expect(Validators.checkUsername('foobar')).to.be.empty
        })
        it('Should return error while empty.',() => {
            expect(Validators.checkUsername('')).to.equal('用户名必须为1-15个字')
        })
        it('Should return error while more then 15 words.',() => {
            expect(Validators.checkUsername('abcdefghijklmnop')).to.equal('用户名必须为1-15个字')
            expect(Validators.checkUsername('一二三四五六七八九十一二三四五六')).to.equal('用户名必须为1-15个字')
        })
    })
})

describe可以多次嵌套使用,更清晰的描述测试功能的结构。执行单元测试:
babel-node ./node_modules/karma/bin/karma start build/karma.conf

三、component测试

在 redux 的理念中,react 组件应该分为视觉组件 component 和 高阶组件 container,UI与逻辑分离,更利于测试。redux 的 example 里,这两种组件一般都分开文件去存放。本人认为,如果视觉组件需要多次复用,应该与container分开来写,但如果基本不复用,或者可以复用的组件已经专门组件化了(下面例子就是),那就没必要分开写,可以写在一个文件里更方便管理,然后通过 exportexport default 分别输出

/* componets/Register.js  */

import React,{ Component,PropTypes } from 'react'
import { connect } from 'react-redux'
import {
  FormGroup,FormControl,Formlabel,FormError,FormTip,Button,TextInput
} from 'componentPath/basic/form'

export class Register extends Component {
  render () {
    const { register,onChangeUsername,onSubmit } = this.props
    <div style={{padding: '50px 130px'}}>
      <FormGroup>
        <Formlabel>用户名</Formlabel>
        <FormControl>
          <TextInput width='370px' limit={15} value={register.username} onChange={onChangeUsername} />
          <FormTip>请输入用户名</FormTip>
          <FormError>{register.usernameError}</FormError>
        </FormControl>
      </FormGroup>
      <FormGroup>
        <Button type='primary' onClick={onSubmit}>提交</Button>
      </FormGroup>
    </div>
  }
}

Register.propTypes = {
  register: PropTypes.object.isrequired,onChangeUsername: PropTypes.func.isrequired,onSubmit: PropTypes.func.isrequired
}

const mapStatetoProps = (state) => {
  return {
    register: state.register
  }
}

const mapdispatchToProps = (dispatch) => {
  return {
    onChangeUsername: name => {
      ...
    },onSubmit: () => {
      ...
    }
  }
}

export default connect(mapStatetoProps,mapdispatchToProps)(Register)

测试 componet,这里用到 enzymesinon

import React from 'react'
import { bindActionCreators } from 'redux'
import { Register } from 'components/Register'
import { shallow } from 'enzyme'
import {
  FormGroup,Dropdown,TextInput
} from 'componentPath/basic/form'

describe('rdappmsg/Trade_edit/componets/Plan',() => {
  let _props,_spies,_wrapper
  let register = {
    username: '',usernameError: ''
  }

  beforeEach(() => {
    _spies = {}
    _props = {
      register,...bindActionCreators({
        onChangeUsername: (_spies.onChangeUsername = sinon.spy()),onSubmit: (_spies.onSubmit = sinon.spy())
      },_spies.dispatch = sinon.spy())
    }
    _wrapper = shallow(<Register {..._props} />)
  })

  it('Should render as a <div>.',() => {
    expect(_wrapper.is('div')).to.equal(true)
  })

  it('Should has two children.',() => {
    expect(_wrapper.children()).to.have.length(2);
  })

  it('Each element of form should be <FormGroup>.',() => {
      _wrapper.children().forEach(function (node) {
        expect(node.is(FormGroup)).to.equal(true);
      })
  })

  it('Should render username properly.',() => {
    expect(_wrapper.find(TextInput).prop('value')).to.be.empty
    _wrapper.setProps({register: {...register,username: 'foobar' }})
    expect(_wrapper.find(TextInput).prop('value')).to.equal('foobar')
  })

  it('Should call onChangeUsername.',() => {
    _spies.onChangeUsername.should.have.not.been.called
    _wrapper.find(TextInput).prop('onChange')('hello')
    _spies.dispatch.should.have.been.called
    
  })
})

beforeEach函数在每个测试用例启动前做一些初始化工作

enzyme shallow用法跟 jquery 的dom操作类似,可以通过选择器过滤出想要的节点,可以接受 css 选择器或者react class,如:find('.someClass')find(TextInput)

这里用到了 sinon 的spies,可以观察到函数调用情况。他还提供stub,mock功能,了解更多请 google

四、action 的测试

先来看一个普通的 action:

/* actions/register.js */

import * as Validator from 'helpers/validator'

export const CHANGE_USERNAME_ERROR = 'CHANGE_USERNAME_ERROR'

export function checkUsername (name) {
  return {
    type: CHANGE_USERNAME_ERROR,error: Validator.checkUsername(name)
  }
}

普通的 action 就是一个简单的函数,返回一个 object,测试起来跟前面的简单函数例子一样:

/* tests/actions/register.js */

import * as Actions from 'actions/register'

describe('actions/register',() => {
  describe('Action: checkUsername',() => {
    it('Should export a constant CHANGE_USERNAME_ERROR.',() => {
      expect(Actions.CHANGE_USERNAME_ERROR).to.equal('CHANGE_USERNAME_ERROR')
    })

    it('Should be exported as a function.',() => {
      expect(Actions.checkUsername).to.be.a('function')
    })
    
    it('Should be return an action.',() => {
      const action = Actions.checkUsername('foobar')
      expect(action).to.have.property('type',Actions.CHANGE_USERNAME_ERROR)
    })
    
    it('Should be return an action with error while input empty name.',() => {
      const action = Actions.checkUsername('')
      expect(action).to.have.property('error').to.not.be.empty
    })   
  })
   
})

再来看一下异步 action,这里功能是改变 username 的同时发起检查:

export const CHANGE_USERNAME = 'CHANGE_USERNAME'

export function changeUsername (name) {
  return (dispatch) => {
    dispatch({
      type: CHANGE_USERNAME,name
    })
    dispatch(checkUsername(name))
  }
}

测试代码

/* tests/actions/register.js */

import * as Actions from 'actions/register'

describe('actions/register',() => {
  let actions
  let dispatchSpy
  let getStateSpy

  beforeEach(function() {
    actions = []
    dispatchSpy = sinon.spy(action => {
      actions.push(action)
    })
  })

  describe('Action: changeUsername',() => {
    it('Should export a constant CHANGE_USERNAME.',() => {
      expect(Actions.CHANGE_USERNAME).to.equal('CHANGE_USERNAME')
    })

    it('Should be exported as a function.',() => {
      expect(Actions.changeUsername).to.be.a('function')
    })
    
    it('Should return a function (is a thunk).',() => {
      expect(Actions.changeUsername()).to.be.a('function')
    })
    
    it('Should be return an action.',Actions.CHANGE_USERNAME_ERROR)
    })
    
    it('Should call dispatch CHANGE_USERNAME and CHANGE_USERNAME_ERROR.',() => {
      Actions.changeUsername('hello')(dispatchSpy)
      dispatchSpy.should.have.been.calledTwice

      expect(actions[0]).to.have.property('type',Actions.CHANGE_USERNAME)
      expect(actions[0]).to.have.property('name','hello')
      expect(actions[1]).to.have.property('type',Actions.CHANGE_USERNAME_ERROR)
      expect(actions[1]).to.have.property('error','')
    }) 
  })
})

假如现在产品需求变更,要求实时在后台检查 username 的合法性,就需要用到 ajax 了,这里假设使用 Jquery 来实现 ajax 请求:

/* actions/register.js */

export const CHANGE_USERNAME_ERROR = 'CHANGE_USERNAME_ERROR'

export function checkUsername (name) {
  return (dispatch) => {
    $.get('/check',{username: name},(msg) => {
      dispatch({
        type: CHANGE_USERNAME_ERROR,error: msg
      })
    })
  }
}

要测试 ajax 请求,可以用 sinon 的 fake XMLHttpRequest,不用为了测试改动 action 任何代码:

/* tests/actions/register.js */

import * as Actions from 'actions/register'

describe('actions/register',() => {
  let actions
  let dispatchSpy
  let getStateSpy
  let xhr
  let requests

  beforeEach(function() {
    actions = []
    dispatchSpy = sinon.spy(action => {
      actions.push(action)
    })
    
    xhr = sinon.useFakeXMLHttpRequest()
    requests = []
    xhr.onCreate = function(xhr) {
      requests.push(xhr);
    };
  })

  afterEach(function() {
    xhr.restore();
  });

  describe('Action: checkUsername',() => {   
    it('Should call dispatch CHANGE_USERNAME_ERROR.',() => {
      Actions.checkUsername('foo@bar')(dispatchSpy)      
      const body = '不能含有特殊字符'
      
      // 手动设置 ajax response      
      requests[0].respond(200,{'Content-Type': 'text/plain'},body)  
          
      expect(actions[0]).to.have.property('type',Actions. CHANGE_USERNAME_ERROR)
      expect(actions[0]).to.have.property('error','不能含有特殊字符')
    }) 
  })
})

五、 reducer 的测试

reducer 就是一个普通函数 (state,action) => newState,测试方法参考第三部分

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如果组件之中有复用的代码,需要重新创建一个父类,父类中存储公共代码,返回子类,同时把公用属性...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例如我们的 setState 函数式同步执行的,我们的事件处理直接绑定在了 dom 元素上,这些都跟 re...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom 转为真实 dom 进行挂载。其实函数是组件和类组件也是在这个基础上包裹了一层,一个是调...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使用,可能是不了解。我公司的项目就没有使用,但是在很多三方库中都有使用。本小节我们来学习下如果使用该...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接触 react 就一直使用 mobx 库,上手简单不复杂。
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc 端可以使用分页进行渲染数限制,在移动端可以使用下拉加载更多。但是对于大量的列表渲染,特别像有实时数据...
本小节开始前,我们先答复下一个同学的问题。上一小节发布后,有小伙伴后台来信问到:‘小编你只讲了类组件中怎么使用 ref,那在函数式组件中怎么使用呢?’。确实我们...
上一小节我们了解了固定高度的滚动列表实现,因为是固定高度所以容器总高度和每个元素的 size、offset 很容易得到,这种场景也适合我们常见的大部分场景,例如...
上一小节我们处理了 setState 的批量更新机制,但是我们有两个遗漏点,一个是源码中的 setState 可以传入函数,同时 setState 可以传入第二...
我们知道 react 进行页面渲染或者刷新的时候,会从根节点到子节点全部执行一遍,即使子组件中没有状态的改变,也会执行。这就造成了性能不必要的浪费。之前我们了解...
在平时工作中的某些场景下,你可能想在整个组件树中传递数据,但却不想手动地通过 props 属性在每一层传递属性,contextAPI 应用而生。
楼主最近入职新单位了,恰好新单位使用的技术栈是 react,因为之前一直进行的是 vue2/vue3 和小程序开发,对于这些技术栈实现机制也有一些了解,最少面试...
我们上一节了了解了函数式组件和类组件的处理方式,本质就是处理基于 babel 处理后的 type 类型,最后还是要处理虚拟 dom。本小节我们学习下组件的更新机...
前面几节我们学习了解了 react 的渲染机制和生命周期,本节我们正式进入基本面试必考的核心地带 -- diff 算法,了解如何优化和复用 dom 操作的,还有...
我们在之前已经学习过 react 生命周期,但是在 16 版本中 will 类的生命周期进行了废除,虽然依然可以用,但是需要加上 UNSAFE 开头,表示是不安...
上一小节我们学习了 react 中类组件的优化方式,对于 hooks 为主流的函数式编程,react 也提供了优化方式 memo 方法,本小节我们来了解下它的用...
开源不易,感谢你的支持,❤ star me if you like concent ^_^
hel-micro,模块联邦sdk化,免构建、热更新、工具链无关的微模块方案 ,欢迎关注与了解
本文主题围绕concent的setup和react的五把钩子来展开,既然提到了setup就离不开composition api这个关键词,准确的说setup是由...
ReactsetState的执行是异步还是同步官方文档是这么说的setState()doesnotalwaysimmediatelyupdatethecomponent.Itmaybatchordefertheupdateuntillater.Thismakesreadingthis.staterightaftercallingsetState()apotentialpitfall.Instead,usecom