Skip to content

Commit

Permalink
tests: add test for getRoot
Browse files Browse the repository at this point in the history
  • Loading branch information
tjx666 committed Apr 3, 2024
1 parent d8fb49b commit ffba9ef
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 15 deletions.
9 changes: 9 additions & 0 deletions src/utils/path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,12 @@ export function trimRightSlash(str: string) {
export function trimLeftSlash(str: string) {
return str.replace(/\/*$/, '');
}

export function getRoot(filePath: string) {
if (/^\.\.?[/\\]/.test(filePath)) throw new Error("filePath can't be relative path");

// unix system
if (filePath.startsWith('/')) return '/';

return filePath.split(/[/\\]/)[0];
}
33 changes: 18 additions & 15 deletions test/index.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
/* eslint-disable promise/no-callback-in-promise */
import path from 'node:path';

import { glob } from 'glob';
import Mocha from 'mocha';

export async function run(
testsRoot: string,
callback: (error: any, failures?: number) => void,
): Promise<void> {
/**
* !: must be synchronized
*/
export function run(testsRoot: string, cb: (error: any, failures?: number) => void): void {
const mocha = new Mocha({ color: true });

try {
const files = await glob('**/**.test.js', { cwd: testsRoot });
for (const f of files) {
mocha.addFile(path.resolve(testsRoot, f));
}
mocha.run((failures) => {
callback(null, failures);
});
} catch (error) {
callback(error);
}
glob('**/**.test.js', { cwd: testsRoot })
.then((files) => {
for (const f of files) mocha.addFile(path.resolve(testsRoot, f));

try {
mocha.run((failures) => {
cb(null, failures);
});
} catch (error) {
cb(error);
}
})
.catch((error) => cb(error));
}
16 changes: 16 additions & 0 deletions test/utils/path.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { strictEqual, throws } from 'node:assert';

import { describe } from 'mocha';

import { getRoot } from '../../src/utils/path';

describe('utils.path', () => {
it('getRoot', () => {
strictEqual(getRoot('/a/b/c'), '/');
strictEqual(getRoot('/a'), '/');
strictEqual(getRoot('/'), '/');
strictEqual(getRoot('c:\\a\\b'), 'c:');
strictEqual(getRoot('c:'), 'c:');
throws(() => getRoot('../a/b'));
});
});

0 comments on commit ffba9ef

Please sign in to comment.