react 单元测试入门

前端之家收集整理的这篇文章主要介绍了react 单元测试入门前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.引入react-addons-test-utils
2.引入断言器 chai
3.安装mocha
4.运行测试(mocha –compilers js:babel-core/register )
需要配置mocha 支持es6及jsx,mocha 自动执行test文件夹下的所有测试用例

babel配置

  1. {
  2. "presets": [ "es2015",'react' ] }

参考文档:http://www.ruanyifeng.com/blog/2016/02/react-testing-tutorial.html
http://www.ruanyifeng.com/blog/2015/12/a-mocha-tutorial-of-examples.html
最简单demo

  1. import TestUtils from 'react-addons-test-utils';
  2. import { expect } from 'chai';
  3.  
  4. import React,{Component} from 'react';
  5. import ReactDOM from 'react-dom';
  6.  
  7. class App extends Component {
  8. render() {
  9. return <h1>test</h1>
  10. }
  11. }
  12.  
  13. function shallowRender(Component) {
  14. const renderer = TestUtils.createRenderer();
  15. renderer.render(<Component/>);
  16. return renderer.getRenderOutput();
  17. }
  18. describe('Shallow Rendering',function () {
  19. it('App\'s title should be Todos',function () {
  20. const app = shallowRender(App);
  21. expect(app.props.children[0].type).to.equal('h1');
  22. expect(app.props.children[0].props.children).to.equal('test');
  23. });
  24. });

猜你在找的React相关文章