Skip to content

Commit

Permalink
tests: add tests for project root finder util (#1483)
Browse files Browse the repository at this point in the history
  • Loading branch information
anshumanv authored Apr 28, 2020
1 parent 4fd9005 commit f6ead01
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
1 change: 1 addition & 0 deletions packages/utils/__tests__/find-project-root/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
Original file line number Diff line number Diff line change
@@ -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, '..'));
});
});
6 changes: 3 additions & 3 deletions packages/utils/src/path-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit f6ead01

Please sign in to comment.