From 52870545df66d9b391bb7200dfccf4490406bf46 Mon Sep 17 00:00:00 2001 From: Suneil Nyamathi Date: Wed, 14 Aug 2024 01:02:46 -0700 Subject: [PATCH] test: add test for memory leak (#3450) * test: add test for memory leak * lint --- test/fetch/response.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/test/fetch/response.js b/test/fetch/response.js index 912c24a40e3..86c57b13658 100644 --- a/test/fetch/response.js +++ b/test/fetch/response.js @@ -2,6 +2,8 @@ const { test } = require('node:test') const assert = require('node:assert') +const { setImmediate } = require('node:timers/promises') +const { AsyncLocalStorage } = require('node:async_hooks') const { tspl } = require('@matteo.collina/tspl') const { Response, @@ -285,3 +287,29 @@ test('fromInnerResponse', () => { assert.strictEqual(getHeadersList(response[kHeaders]), innerResponse.headersList) assert.strictEqual(getHeadersGuard(response[kHeaders]), 'immutable') }) + +test('clone body garbage collection', async () => { + const asyncLocalStorage = new AsyncLocalStorage() + let ref + + await new Promise(resolve => { + asyncLocalStorage.run(new Map(), async () => { + const res = new Response('hello world') + const clone = res.clone() + + asyncLocalStorage.getStore().set('key', clone) + ref = new WeakRef(clone.body) + + await res.text() + await clone.text() // consume body + + resolve() + }) + }) + + await setImmediate() + global.gc() + + const cloneBody = ref.deref() + assert.equal(cloneBody, undefined, 'clone body was not garbage collected') +})