From 6c9e6344018982ff0a241f6f8a71682546410ebe Mon Sep 17 00:00:00 2001 From: Khafra <42794878+KhafraDev@users.noreply.github.com> Date: Thu, 14 Jul 2022 17:44:02 -0400 Subject: [PATCH] fix(mock utils): set Readable.abort (#1549) --- lib/mock/mock-utils.js | 3 ++- test/mock-pool.js | 25 +++++++++++++++++++++++-- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/lib/mock/mock-utils.js b/lib/mock/mock-utils.js index 14bfcb11879..80052223f8f 100644 --- a/lib/mock/mock-utils.js +++ b/lib/mock/mock-utils.js @@ -8,7 +8,7 @@ const { kOrigin, kGetNetConnect } = require('./mock-symbols') -const { buildURL } = require('../core/util') +const { buildURL, nop } = require('../core/util') function matchValue (match, value) { if (typeof match === 'string') { @@ -288,6 +288,7 @@ function mockDispatch (opts, handler) { const responseHeaders = generateKeyValues(headers) const responseTrailers = generateKeyValues(trailers) + handler.abort = nop handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode)) handler.onData(Buffer.from(responseData)) handler.onComplete(responseTrailers) diff --git a/test/mock-pool.js b/test/mock-pool.js index 929ebeebb93..3e6907192e4 100644 --- a/test/mock-pool.js +++ b/test/mock-pool.js @@ -3,7 +3,7 @@ const { test } = require('tap') const { createServer } = require('http') const { promisify } = require('util') -const { MockAgent, MockPool, setGlobalDispatcher, request } = require('..') +const { MockAgent, MockPool, getGlobalDispatcher, setGlobalDispatcher, request } = require('..') const { kUrl } = require('../lib/core/symbols') const { kDispatches } = require('../lib/mock/mock-symbols') const { InvalidArgumentError } = require('../lib/core/errors') @@ -303,8 +303,29 @@ test('MockPool - basic intercept with MockPool.request', async (t) => { }) }) +// https://github.com/nodejs/undici/issues/1546 +test('MockPool - correct errors when consuming invalid JSON body', async (t) => { + const oldDispatcher = getGlobalDispatcher() + + const mockAgent = new MockAgent() + mockAgent.disableNetConnect() + setGlobalDispatcher(mockAgent) + + t.teardown(() => setGlobalDispatcher(oldDispatcher)) + + const mockPool = mockAgent.get('https://google.com') + mockPool.intercept({ + path: 'https://google.com' + }).reply(200, 'it\'s just a text') + + const { body } = await request('https://google.com') + await t.rejects(body.json(), SyntaxError) + + t.end() +}) + test('MockPool - allows matching headers in fetch', { skip: nodeMajor < 16 }, async (t) => { - const { fetch, getGlobalDispatcher, setGlobalDispatcher } = require('../index') + const { fetch } = require('../index') const oldDispatcher = getGlobalDispatcher()