jameslnewell / xhr-mock

Utility for mocking XMLHttpRequest.
196 stars 48 forks source link

Latest version doesn't work for rxjs/Ajax with json responseType. #50

Closed cicloon closed 6 years ago

cicloon commented 6 years ago

In version 2.0.3, trying to mock xhr requests for an AjaxObservable result in an empty response even if the response is a string, it does work in 2.0.0-preview.13.

For example:

import { ajax } from 'rxjs/observable/dom/ajax';
import { map, retryWhen, scan, delay } from 'rxjs/operators';
import xhrMock from 'xhr-mock';

xhrMock.post('/some-url', {
  body: JSON.stringify({data: 'mockdata'}),  
});

ajax({
  '/some-url',
  body: {some: 'something'},
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  responseType: 'json',
}).subscribe((result) => console.log(result.response)  ); // response is null here

However, it works in 2.0.0-preview.13 passing and object to xhr-mock:

xhrMock.post('/some-url', {
  body: {data: 'mockdata'},  
});
jameslnewell commented 6 years ago

Thanks for raising an issue and providing a test case!!!

I'm not sure it worked exactly as you describe (I don't remember parsing the body string to JSON) but I was probably returning whatever response.body was set to - so that if you had set response.body to an object you could kind of simulate a json response type.

Its now parsing the response as JSON instead of throwing notImplementedError. https://github.com/jameslnewell/xhr-mock/commit/f3f9ca12beaea9c4e5512c360164e9009128d7f2#diff-fc2b05ee8d7a4b0db14802f124924abc

Released in 2.1.0. Let me know if you encounter any issues.