Skip to content

Commit

Permalink
fix: resolve mocha binary from package.json (#138)
Browse files Browse the repository at this point in the history
  • Loading branch information
Danielku15 authored Sep 13, 2024
1 parent a4f818e commit c61b591
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/configurationFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export class ConfigurationFile implements vscode.Disposable {
}

async getMochaSpawnArgs(customArgs: readonly string[]): Promise<string[]> {
this._pathToMocha ??= await this._resolveLocalMochaPath('/bin/mocha.js');
this._pathToMocha ??= await this._resolveLocalMochaBinPath();

return [
await getPathToNode(this.logChannel),
Expand Down Expand Up @@ -133,11 +133,29 @@ export class ConfigurationFile implements vscode.Disposable {
throw new HumanError(`Could not find node_modules above '${mocha}'`);
}

private _resolveLocalMochaPath(suffix?: string): Promise<string> {
private async _resolveLocalMochaBinPath(): Promise<string> {
try {
const packageJsonPath = await this._resolveLocalMochaPath('/package.json');
const packageJson = JSON.parse(await fs.promises.readFile(packageJsonPath, 'utf-8'));
let binPath = packageJson?.bin?.mocha;
if (binPath) {
binPath = path.join(path.dirname(packageJsonPath), binPath);
await fs.promises.access(binPath);
return binPath;
}
} catch (e) {
// ignore
}

this.logChannel.warn('Could not resolve mocha bin path from package.json, fallback to default');
return await this._resolveLocalMochaPath('/bin/mocha.js');
}

private _resolveLocalMochaPath(suffix: string = ''): Promise<string> {
return new Promise<string>((resolve, reject) => {
const dir = path.dirname(this.uri.fsPath);
this.logChannel.debug(`resolving 'mocha${suffix}' via ${dir}`);
this.getResolver().resolve({}, dir, 'mocha' + (suffix ?? ''), {}, (err, res) => {
this.getResolver().resolve({}, dir, 'mocha' + suffix, {}, (err, res) => {
if (err) {
this.logChannel.error(`resolving 'mocha${suffix}' failed with error ${err}`);
reject(
Expand Down

0 comments on commit c61b591

Please sign in to comment.