Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIX: fetch-mock Response.body is not always a stream #610

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions .codeclimate.yml
@@ -1,3 +1,5 @@
exclude_patterns:
- docs
- test/specs
- test/client-specs
- test/server-specs
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