加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何使用sinon在mocha中模拟ajax调用,而不使用回流存储在ractive

发布时间:2020-12-16 02:48:55 所属栏目:百科 来源:网络整理
导读:我有一个工作ractive组件测试用例已经与mocha使用sinon ans能够模拟ajax调用但在setTimeout(function(){},100)的帮助下,我不喜欢使用它. beforeEach(function () { this.container = document.createElement('div'); document.body.appendChild(this.contain
我有一个工作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选项:

If set,the server will respond to every request immediately and
synchronously. This is ideal for faking the server from within a test
without having to call server.respond() after each request made in
that test. As this is synchronous and immediate,this is not suitable
for simulating actual network latency in tests or mockups.

this.server = sinon.fakeServer.create({ respondImmediately: true })

// now no need to call server.respond() and calls are returned synchronously!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读