Question
如何用mocha测试setInterval,
在代码中,将setInterval和clearInterval放在一个函数中,并且用一个公共属性public或private属性来赋值,测试的时候会报错
原因
mocha测试主要是node环境,所以找不到windows对象下的时间
解决方案
先修改开发代码
用组件state来赋值,将setInterval单独放入一个函数,clearInterval单独放入一个函数
/*** #### Starts the timer and update the component's state* @param autoRefreshTimeS is equal component's state interval (s)* ****** ### Attention:* this is asynchronous operations*/private startTimer(autoRefreshTimeS: number) {this.state.logger.debug("Starting timer with interval", autoRefreshTimeS);let second = 0;const timer = setInterval(async () => {this.state.logger.debug("Timer fires. Sending a new image fetching request.",);second++;// if time is equal to interval,fetch imageif (second % autoRefreshTimeS === 0) {this.props.fetchData();}//这里为什么不能直接写timer,而写1000呢?
//因为用户会随时更改timer,写timer易导致不停刷新,浏览器奔溃}, 1000);this.setState({ timer });}/*** #### Stops the timer and updates the component's state* ****** ### Attention:* this is asynchronous operations*/private stopTimer() {this.state.logger.debug("Stopping timer");if (this.state.timer !== null) {clearInterval(this.state.timer);this.setState({ timer: null });}}
测试部分
其实我可能写的不太对,但是目前这么写能够测到
// test Timer APIdescribe("test state about 'timer' ", () => {let galleries;before(() => {//这是你的组件galleries = enzyme.shallow(<GalleryloggerFactory={loggers}translator={translators.object}imageProvider={imageInfoProviderMocks.object}cache={cacheMocks.object}filterProvider={filterProviderMocks.object}generatorUrl={imagePathProviderMocks.object}/>,);});it("select interval value, gallery state about interval
will update,gallery will have 'timer' api, toggle autoRefresh
to make it as false, 'timer' is null", async () => {//下面这句是触发条件// select interval value, gallery will update state about interval and timergalleries.find(TopOption).prop("updateIntervalAndTimer")(1);//下面这句是当timer触发后引起的结果expect(galleries.state("interval")).to.equal(1);//又一个触发条件galleries.setState({ autoRefresh: true, interval: 2000 });//触发后引起的结果expect(galleries.state("timer")).not.equal(null, "");//下面这两句是单纯为了覆盖率,暂时不晓得为什么要这么写galleries.state("timer")._onTimeout();expect(galleries.state("timer")._repeat).equal(1000);//不能让timer保持触发状态,所以下面这句是为了关闭Timergalleries.find(TopOption).prop("updateAutoRefreshAndTimer")(false);});});