Skip to content

Commit

Permalink
FIX: fetch-mock Response.body is not always a stream
Browse files Browse the repository at this point in the history
The WhatWG fetch spec requires that Body.body (and therefore Response.body)
is always a readable stream, but it doesn't always happen that way in Node.
This seems to be because ResponseBuilder tries to fetch the stream module
from fetchMock, but it looks in the wrong place.

Fixes wheresrhys#609
  • Loading branch information
Brian Crowell committed May 15, 2021
1 parent 4b54e6d commit 77a9c7d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
7 changes: 5 additions & 2 deletions src/lib/response-builder.js
Expand Up @@ -137,9 +137,12 @@ e.g. {"body": {"status: "registered"}}`);

// On the server we need to manually construct the readable stream for the
// Response object (on the client this done automatically)
if (this.Stream) {
if (
this.fetchMock.Stream &&
!(this.body instanceof this.fetchMock.Stream.Readable)
) {
this.debug('Creating response stream');
const stream = new this.Stream.Readable();
const stream = new this.fetchMock.Stream.Readable();
if (this.body != null) { //eslint-disable-line
stream.push(this.body, 'utf-8');
}
Expand Down
22 changes: 22 additions & 0 deletions test/server-specs/server-only.test.js
Expand Up @@ -40,6 +40,28 @@ describe('nodejs only tests', () => {
});
});

it('always responds with a readable stream', (done) => {
const { Writable } = require('stream');
const write = sinon.stub().callsFake((chunk, enc, cb) => {
cb();
});
const writable = new Writable({
write,
});

fetchMock.mock(/a/, Buffer.from('response string', 'utf8'), {
sendAsJson: false,
});
fetchMock.fetchHandler('http://a.com').then((res) => {
res.body.pipe(writable);
});

writable.on('finish', () => {
expect(write.args[0][0].toString('utf8')).to.equal('response string');
done();
});
});

// See https://github.com/wheresrhys/fetch-mock/issues/575
it('can respond with large bodies from the interweb', async () => {
const fm = fetchMock.sandbox();
Expand Down
2 changes: 1 addition & 1 deletion test/specs/config/constructors.test.js
Expand Up @@ -130,7 +130,7 @@ describe('custom implementations', () => {
expect(res.isFake).to.be.true;
expect(spiedReplacementResponse.callCount).to.equal(1);
const lastCall = spiedReplacementResponse.lastCall.args;
expect(lastCall[0]).to.equal('hello');
expect(lastCall[0]).to.have.property(Symbol.asyncIterator);
expect(lastCall[1].status).to.equal(200);
expect(defaultSpies.Response.callCount).to.equal(0);
});
Expand Down

0 comments on commit 77a9c7d

Please sign in to comment.