Skip to content

Commit

Permalink
Add a .text() accessor to FetchResponse (#2922)
Browse files Browse the repository at this point in the history
Add a .text() accessor to FetchResponse to allow retrieving text without converting it to JSON first.  (I.e., extending FetchResponse to cover one additional method from the Response / Body API.)
  • Loading branch information
Terran Lane authored and cramforce committed Apr 15, 2016
1 parent 06a7598 commit 65c4b02
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
11 changes: 10 additions & 1 deletion src/xhr.js
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ function assertSuccess(response) {
*
* See https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch
*/
class FetchResponse {
export class FetchResponse {
/**
* @param {!XMLHttpRequest} xhr
*/
Expand Down Expand Up @@ -386,6 +386,15 @@ class FetchResponse {
return Promise.resolve(this.xhr_.responseText);
}

/**
* Drains the response and returns a promise that resolves with the response
* text.
* @return {!Promise<string>}
*/
text() {
return this.drainText_();
}

/**
* Drains the response and returns the JSON object.
* @return {!Promise<!JSONValue>}
Expand Down
49 changes: 48 additions & 1 deletion test/functional/test-xhr.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
*/

import * as sinon from 'sinon';
import {xhrFor, fetchPolyfill} from '../../src/xhr';
import {xhrFor, fetchPolyfill, FetchResponse} from '../../src/xhr';

describe('XHR', function() {
let sandbox;
Expand Down Expand Up @@ -413,4 +413,51 @@ describe('XHR', function() {

});
});

describe('FetchResponse', () => {
const TEST_TEXT = 'this is some test text';
const mockXhr = {
status: 200,
responseText: TEST_TEXT,
};

it('should provide text', () => {
const response = new FetchResponse(mockXhr);
return response.text().then(result => {
expect(result).to.equal(TEST_TEXT);
});
});

it('should provide text only once', () => {
const response = new FetchResponse(mockXhr);
return response.text().then(result => {
expect(result).to.equal(TEST_TEXT);
expect(response.text.bind(response), 'should throw').to.throw(Error,
/Body already used/);
});
});

scenarios.forEach(test => {
if (test.desc === 'Polyfill') {
// FetchRequest is only returned by the Polyfill version of Xhr.
describe('#text', () => {
beforeEach(setupMockXhr);
it('should return text from a full XHR request', () => {
expect(requests[0]).to.be.undefined;
const promise = test.xhr.fetchAmpCors_('http://nowhere.org').then(
response => {
expect(response).to.be.instanceof(FetchResponse);
return response.text().then(result => {
expect(result).to.equal(TEST_TEXT);
});
});
requests[0].respond(200, {
'Content-Type': 'text/plain',
}, TEST_TEXT);
return promise;
});
});
}
});
});
});

0 comments on commit 65c4b02

Please sign in to comment.