react 单元测试入门

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

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

babel配置

{
  "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

import TestUtils from 'react-addons-test-utils';
import { expect } from 'chai';

import React,{Component} from 'react';
import ReactDOM from 'react-dom';

class App extends Component {
    render() {
        return <h1>test</h1>
    }
}

function shallowRender(Component) {
    const renderer = TestUtils.createRenderer();
    renderer.render(<Component/>);
    return renderer.getRenderOutput();
}
describe('Shallow Rendering',function () {
    it('App\'s title should be Todos',function () {
        const app = shallowRender(App);
        expect(app.props.children[0].type).to.equal('h1');
        expect(app.props.children[0].props.children).to.equal('test');
    });
});

猜你在找的React相关文章