Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter requests in Sinon

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.com", [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.

like image 209
oleg_star Avatar asked Feb 25 '13 16:02

oleg_star


1 Answers

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

server.respondWith("GET", "http:\\example.com", [200, {"Content-Type": "application/json"}, '{"Body:""asd"}'])
like image 156
Andreas Köberle Avatar answered Sep 24 '22 09:09

Andreas Köberle