【问题标题】:How to filter requests in SinonSinon中如何过滤请求
【发布时间】:2013-02-25 16:55:21
【问题描述】:

我正在 Jasmine 中为 Backbone 应用程序编写单元测试。当然,我在测试中使用了 Sinon。但现在我有问题。我正在为登录屏幕编写测试,我需要模拟服务器响应 - 因为服务器工作得非常糟糕。现在我的代码看起来:

describe('Login', function(){
     it('Should simulate server response', function(){
        server = sinon.fakeServer.create();
        server.respondWith("GET", "http:\\example.com", [200, {"Content-Type": "application/json"}, '{"Body:""asd"}'])
     })
     $('body').find('button#login').trigger('click');
     server.respond();
     server.restore()
     console.log(server.requests);
})

这段代码工作正常,但我在控制台中看到伪造所有请求,但在登录期间我也有其他请求,我不需要为它们使用假服务器。这是对下一个屏幕的请求。可能存在对特殊请求进行过滤或使用虚假响应的方法。请帮帮我。谢谢。

【问题讨论】:

    标签: javascript jasmine sinon


    【解决方案1】:

    诀窍是在服务器的FakeXMLHttpRequest 对象上使用过滤器。那么只有你过滤掉的请求才会使用假服务器:

    server = sinon.fakeServer.create();
    server.xhr.useFilters = true;
    
    server.xhr.addFilter(function(method, url) {
      //whenever the this returns true the request will not faked
      return !url.match(/example.com/);
    });
    
    server.respondWith("GET", "http:\\example.com", [200, {"Content-Type": "application/json"}, '{"Body:""asd"}'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-15
      • 1970-01-01
      • 2016-10-18
      • 2014-10-27
      • 1970-01-01
      • 2014-12-22
      • 2023-04-08
      • 1970-01-01
      相关资源
      最近更新 更多