> React v15.1.0
> Jest v12.1.1
>酶v2.3.0
> Jest v12.1.1
>酶v2.3.0
我试图弄清楚如何测试一个在单击调用的函数中调用promise的组件.我期待Jest的runAllTicks()函数来帮助我,但它似乎没有执行诺言.
零件:
import React from 'react'; import Promise from 'bluebird'; function doSomethingWithAPromise() { return new Promise((resolve) => { setTimeout(() => { resolve(); },50); }); } export default class AsyncTest extends React.Component { constructor(props) { super(props); this.state = { promiseText: '',timeoutText: '' }; this.setTextWithPromise = this.setTextWithPromise.bind(this); this.setTextWithTimeout = this.setTextWithTimeout.bind(this); } setTextWithPromise() { return doSomethingWithAPromise() .then(() => { this.setState({ promiseText: 'there is text!' }); }); } setTextWithTimeout() { setTimeout(() => { this.setState({ timeoutText: 'there is text!' }); },50); } render() { return ( <div> <div id="promiseText">{this.state.promiseText}</div> <button id="promiseBtn" onClick={this.setTextWithPromise}>Promise</button> <div id="timeoutText">{this.state.timeoutText}</div> <button id="timeoutBtn" onClick={this.setTextWithTimeout}>Timeout</button> </div> ); } }
测试:
import AsyncTest from '../async'; import { shallow } from 'enzyme'; import React from 'react'; jest.unmock('../async'); describe('async-test.js',() => { let wrapper; beforeEach(() => { wrapper = shallow(<AsyncTest />); }); // FAIL it('displays the promise text after click of the button',() => { wrapper.find('#promiseBtn').simulate('click'); jest.runAllTicks(); jest.runAllTimers(); wrapper.update(); expect(wrapper.find('#promiseText').text()).toEqual('there is text!'); }); // PASS it('displays the timeout text after click of the button',() => { wrapper.find('#timeoutBtn').simulate('click'); jest.runAllTimers(); wrapper.update(); expect(wrapper.find('#timeoutText').text()).toEqual('there is text!'); }); });
在结束测试之前,没有什么需要以某种方式等待承诺完成.从我的代码中我可以看到有两种主要的方法.
>独立测试onClick和你的承诺方法.因此,检查onClick调用正确的函数,但是监视setTextWithPromise,触发单击并断言setTextWithPromise被调用.然后你也可以得到组件实例并调用那个返回promise的方法,你可以附加一个处理程序并断言它做了正确的事情.>公开一个回调道具,你可以传递在promise解析时调用的回调道具.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。