diff --git a/packages/utils/__tests__/find-project-root/package.json b/packages/utils/__tests__/find-project-root/package.json new file mode 100644 index 00000000000..0967ef424bc --- /dev/null +++ b/packages/utils/__tests__/find-project-root/package.json @@ -0,0 +1 @@ +{} diff --git a/packages/utils/__tests__/find-project-root/project/find-project-root.test.ts b/packages/utils/__tests__/find-project-root/project/find-project-root.test.ts new file mode 100644 index 00000000000..83100a33386 --- /dev/null +++ b/packages/utils/__tests__/find-project-root/project/find-project-root.test.ts @@ -0,0 +1,24 @@ +// eslint-disable-next-line node/no-unpublished-import +import { findProjectRoot } from '../../../src/path-utils'; +import { join } from 'path'; + +beforeAll(() => { + // This sets the project root as the root dir, needed since some tests change process cwd. + process.chdir(join(__dirname, '../../../../../')); +}); + +describe('findProjectRoot function', () => { + it('works correctly', () => { + /* when no directory is passed, it takes the current process working directory as starting point + which contains package.json thus it should be the project root */ + const projectRoot = findProjectRoot(); + expect(projectRoot).toEqual(process.cwd()); + }); + + it('works correctly with a non-default dir', () => { + /* when passing a custom directory, it's used as the starting point and so it should yield the path + nearest package.json from the given directory */ + const projectRoot = findProjectRoot(__dirname); + expect(projectRoot).toEqual(join(__dirname, '..')); + }); +}); diff --git a/packages/utils/src/path-utils.ts b/packages/utils/src/path-utils.ts index 35c935bb00e..73e8d4aa207 100644 --- a/packages/utils/src/path-utils.ts +++ b/packages/utils/src/path-utils.ts @@ -19,12 +19,12 @@ export function isLocalPath(str: string): boolean { /** * Find the root directory path of a project. - * + * @param {String} cwd - Any custom starting point to walk through directories * @returns {String} Absolute path of the project root. */ -export function findProjectRoot(): string { - const rootFilePath = findup('package.json'); +export function findProjectRoot(cwd = process.cwd()): string { + const rootFilePath = findup('package.json', { cwd }); const projectRoot = path.dirname(rootFilePath); return projectRoot; }