jameslnewell / xhr-mock

Utility for mocking XMLHttpRequest.
196 stars 48 forks source link

Cannot test timeout scenarios #29

Closed nikwen closed 7 years ago

nikwen commented 7 years ago

Great library!

However, I did not find a way to test my timeout handlers. Basically, I want the fake server to hang and not answer anything so that my timeout handler steps in.

See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/timeout

jameslnewell commented 7 years ago
var mock = require('xhr-mock');

//replace the real XHR object with the mock XHR object
mock.setup();

//create a mock response for all POST requests with the URL http://localhost/api/user
mock.post('http://localhost/api/user', function(req, res) {
  return res.timeout(true); //simulate a timeout
});

//create an instance of the (mock) XHR object and use as per normal
var xhr = new XMLHttpRequest();
...

xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {

    //when you're finished put the real XHR object back
    mock.teardown();

  }
}

^^^ doesn't work for you? https://github.com/jameslnewell/xhr-mock#timeout--boolnumber

nikwen commented 7 years ago

Thanks a lot for your reply! :)

I seriously don't know how I missed that function. Works perfectly. 🎉