首页 > 网站 > WEB开发 > 正文

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

2024-04-27 15:18:14
字体:
来源:转载
供稿:网友

参考文档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 = docglobal.window = doc.defaultViewclass 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'); });});
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表