Skip to content

Commit

Permalink
fix(core): ModuleLoader.hasAvailable checks if a given dependency is …
Browse files Browse the repository at this point in the history
…available
  • Loading branch information
jan-molak committed Jan 2, 2021
1 parent 1ad82e1 commit f67c982
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
21 changes: 19 additions & 2 deletions packages/core/spec/io/ModuleLoader.spec.ts
@@ -1,19 +1,20 @@
import 'mocha';

import path = require('path');
import { ModuleLoader, Version } from '../../src/io';
import { expect } from '../expect';

describe('ModuleLoader', () => {

it('returns the major version number of a given package', () => {
it('returns the version number of a given package', () => {
const loader = new ModuleLoader(__dirname);

const expectedVersion = require('../../package.json').version;

expect(loader.versionOf('../../')).to.equal(new Version(expectedVersion));
});

it('returns the major version of the npm-resolved package if the local package could not be found', () => {
it('returns the version of the npm-resolved package if the local package could not be found', () => {
const loader = new ModuleLoader(path.join(__dirname, 'non-existent', 'local', 'directory'));

const expectedVersion = require('tiny-types/package.json').version; // tslint:disable-line:no-submodule-imports
Expand All @@ -23,6 +24,22 @@ describe('ModuleLoader', () => {

it('complains if neither a local version or the npm-resolved version could not be found', () => {
const loader = new ModuleLoader(__dirname);

expect(() => loader.versionOf('non-existent-module')).to.throw(Error, `Cannot find module 'non-existent-module/package'`);
});

describe('when checking if a given module is available to be required', () => {

it('returns true if the module is available', () => {
const loader = new ModuleLoader(__dirname);

expect(loader.hasAvailable('tiny-types')).to.equal(true);
});

it('returns false if the module is not available', () => {
const loader = new ModuleLoader(__dirname);

expect(loader.hasAvailable('non-existent-module')).to.equal(false);
});
});
});
18 changes: 18 additions & 0 deletions packages/core/src/io/ModuleLoader.ts
Expand Up @@ -2,10 +2,28 @@ const Module = require('module'); // tslint:disable-line:no-var-requ
import * as path from 'path';
import { Version } from './Version';

/**
* @package
*/
export class ModuleLoader {
constructor(public readonly cwd: string) {
}

/**
* @desc
* Returns true if a given module is available to be required, false otherwise.
*
* @param {string} moduleId
* NPM module id, for example 'cucumber' or '@serenity-js/core'
*/
hasAvailable(moduleId: string): boolean {
try {
return !! this.require(moduleId);
} catch (e) {
return false;
}
}

/**
* @package
*
Expand Down

0 comments on commit f67c982

Please sign in to comment.