From fe6853524e51faaba0c7cd16203f2384fe9040d3 Mon Sep 17 00:00:00 2001 From: Dorian Niemiec Date: Mon, 2 Sep 2024 13:08:05 +0200 Subject: [PATCH] test: mock "path" module in forbidden path utility function unit tests --- src/utils/forbiddenPaths.js | 5 ++--- tests/utils/forbiddenPaths.test.js | 12 ++++++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/utils/forbiddenPaths.js b/src/utils/forbiddenPaths.js index e4f517a..48e49d0 100644 --- a/src/utils/forbiddenPaths.js +++ b/src/utils/forbiddenPaths.js @@ -4,17 +4,16 @@ const path = require("path"); // Function to get URL path for use in forbidden path adding. function getInitializePath(to) { const isWin32 = os.platform() == "win32"; - const pathModS = isWin32 ? path.win32 : path.posix; // pathModS needed just for the test suite const cwd = process.cwd(); if (isWin32) { to = to.replace(/\//g, "\\"); if (to[0] == "\\") to = cwd.split("\\")[0] + to; } - const absoluteTo = pathModS.isAbsolute(to) + const absoluteTo = path.isAbsolute(to) ? to : process.dirname + (isWin32 ? "\\" : "/") + to; if (isWin32 && cwd[0] != absoluteTo[0]) return ""; - const relative = pathModS.relative(cwd, absoluteTo); + const relative = path.relative(cwd, absoluteTo); if (isWin32) { return "/" + relative.replace(/\\/g, "/"); } else { diff --git a/tests/utils/forbiddenPaths.test.js b/tests/utils/forbiddenPaths.test.js index 9c77867..61f66a8 100644 --- a/tests/utils/forbiddenPaths.test.js +++ b/tests/utils/forbiddenPaths.test.js @@ -9,6 +9,18 @@ const os = require("os"); jest.mock("os", () => ({ platform: jest.fn() })); +jest.mock("path", () => { + const path = jest.requireActual("path"); + const os = require("os"); + return { + isAbsolute: (...params) => + (os.platform() == "win32" ? path.win32 : path.posix).isAbsolute( + ...params + ), + relative: (...params) => + (os.platform() == "win32" ? path.win32 : path.posix).relative(...params) + }; +}); describe("Forbidden paths handling", () => { beforeEach(() => {