react 单元测试,模拟操作后数据的变化

前端之家收集整理的这篇文章主要介绍了react 单元测试,模拟操作后数据的变化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

参考文档https://github.com/airbnb/enzyme/issues/341
http://www.ruanyifeng.com/blog/2016/02/react-testing-tutorial.html

1.引入enzyme 的mount
2.引入jsdom
3.调用simulate 模拟操作
4.断言结果是否是预期

import {mount} from 'enzyme';

import { expect } from 'chai';

import React,{Component} from 'react';
import ReactDOM from 'react-dom';
import jsdom from 'jsdom'
const doc = jsdom.jsdom('<!doctype html><html><body></body></html>')
global.document = doc
global.window = doc.defaultView


class App extends Component {
    constructor(props) {
        super(props)
        this.state = {
            count: 1
        }
    }
    render() {
        return <h1 onClick={()=>{ this.setState({
            count: this.state.count + 1
        }) }}>{this.state.count}</h1>
    }
}

function shallowRender(Component) {
    const renderer = TestUtils.createRenderer();
    renderer.render(<Component/>);
    return renderer.getRenderOutput();
}
describe('Shallow Rendering',function () {
    it('countTest',function () {
        let app = mount(<App/>);
        app.find('h1').simulate('click');
        expect(app.find('h1').text()).to.equal('2');

    });
});
原文链接:https://www.f2er.com/react/304877.html

猜你在找的React相关文章