From aac8ba7bd7a361e06f6c08978644b9904c81bcb6 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Wed, 25 Sep 2024 19:34:58 +0200 Subject: [PATCH] test_runner: fix mocking modules with quote in their URL PR-URL: https://github.com/nodejs/node/pull/55083 Reviewed-By: Colin Ihrig Reviewed-By: Tierney Cyren Reviewed-By: Mohammed Keyvanzadeh Reviewed-By: Chemi Atlow --- lib/internal/test_runner/mock/loader.js | 2 +- test/fixtures/module-mocking/don't-open.mjs | 1 + test/parallel/test-runner-module-mocking.js | 9 +++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 test/fixtures/module-mocking/don't-open.mjs diff --git a/lib/internal/test_runner/mock/loader.js b/lib/internal/test_runner/mock/loader.js index 29d1ef70ebf9fc..bfdfe93741c2cc 100644 --- a/lib/internal/test_runner/mock/loader.js +++ b/lib/internal/test_runner/mock/loader.js @@ -139,7 +139,7 @@ async function createSourceFromMock(mock, format) { const { exportNames, hasDefaultExport, url } = mock; const useESM = format === 'module' || format === 'module-typescript'; const source = `${testImportSource(useESM)} -if (!$__test.mock._mockExports.has('${url}')) { +if (!$__test.mock._mockExports.has(${JSONStringify(url)})) { throw new Error(${JSONStringify(`mock exports not found for "${url}"`)}); } diff --git a/test/fixtures/module-mocking/don't-open.mjs b/test/fixtures/module-mocking/don't-open.mjs new file mode 100644 index 00000000000000..f2b47223e34a83 --- /dev/null +++ b/test/fixtures/module-mocking/don't-open.mjs @@ -0,0 +1 @@ +export let string = 'original esm string'; diff --git a/test/parallel/test-runner-module-mocking.js b/test/parallel/test-runner-module-mocking.js index f36dc13915b51a..dd200eb839ed3d 100644 --- a/test/parallel/test-runner-module-mocking.js +++ b/test/parallel/test-runner-module-mocking.js @@ -413,6 +413,15 @@ test('modules cannot be mocked multiple times at once', async (t) => { t.mock.module(fixture, { namedExports: { fn() { return 42; } } }); await assert.rejects(import(fixture), { code: 'ERR_UNSUPPORTED_ESM_URL_SCHEME' }); }); + + await t.test('Importing a module with a quote in its URL should work', async (t) => { + const fixture = fixtures.fileURL('module-mocking', 'don\'t-open.mjs'); + t.mock.module(fixture, { namedExports: { fn() { return 42; } } }); + + const mocked = await import(fixture); + + assert.strictEqual(mocked.fn(), 42); + }); }); test('mocks are automatically restored', async (t) => {