如何使用sinon在mocha中模拟ajax调用,而不使用回流存储在ractive
我有一个工作ractive组件测试用例已经与mocha使用sinon ans能够模拟ajax调用但在setTimeout(function(){},100)的帮助下,我不喜欢使用它.
beforeEach(function () { this.container = document.createElement('div'); document.body.appendChild(this.container); this.server = sinon.fakeServer.create(); this.server.respondWith( "GET","/api/url",[ 200,{ "Content-Type": "application/json" },'{"data": []}' ] ); }); afterEach(function () { document.body.removeChild(this.container); }); it("should fetch data from server",function (done) { var server = this.server; var Component = require('rvc!path/to/component'); var component = new Component({ el: this.container,}); setTimeout( function() { server.respond(); expect(component.findAll('.list li').length).to.equal(7); done(); },100); }); 正如您在上面的代码中所看到的,我正在使用setTimeout来确保在对组件进行实际测试之前进行了ajax调用(mock). 有没有办法可以消除具有相同效果的setTimeout?谢谢! 解决方法
假设您的http请求发生在组件中,那么在事件循环的下一个滴答之前它将不会获取数据.
一种方法是使用setTimeout,但你可能可以降低超时(使用autoRespondAfter来调整sinon响应延迟). 如果您的组件代码支持它,那么看起来非常适合您在sinon fakeServer docs中的用例的方法是使用respondImmediately选项:
this.server = sinon.fakeServer.create({ respondImmediately: true }) // now no need to call server.respond() and calls are returned synchronously! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |