最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to filter requests in Sinon - Stack Overflow

programmeradmin0浏览0评论

I am writing unit tests in Jasmine for Backbone application. And of course I use Sinon in my tests. But now I have problem. I am writing tests for Login screen and I need simulate server responce - because server works very bad. Now my code looks:

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

And this code works fine, but I see in console that fakes all requests, but during Login I also have other requests, and I don't need use fake server for them. It is requests for next screen. Maybe exist way to make filter or use fake responds for special requests. Help me please. Thanks.

I am writing unit tests in Jasmine for Backbone application. And of course I use Sinon in my tests. But now I have problem. I am writing tests for Login screen and I need simulate server responce - because server works very bad. Now my code looks:

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

And this code works fine, but I see in console that fakes all requests, but during Login I also have other requests, and I don't need use fake server for them. It is requests for next screen. Maybe exist way to make filter or use fake responds for special requests. Help me please. Thanks.

Share Improve this question edited Jun 29, 2016 at 12:55 Andreas Köberle 111k58 gold badges280 silver badges307 bronze badges asked Feb 25, 2013 at 16:55 oleg_staroleg_star 2462 silver badges11 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

The trick is to use filters on the FakeXMLHttpRequest object of the server. Then only the request you filter out will use the fake server:

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./);
});

server.respondWith("GET", "http:\\example.", [200, {"Content-Type": "application/json"}, '{"Body:""asd"}'])
发布评论

评论列表(0)

  1. 暂无评论