diff --git a/index.js b/index.js index 98ad806..1bcaf78 100644 --- a/index.js +++ b/index.js @@ -15,7 +15,11 @@ const parentDir = path.dirname(module.parent.filename); class Conf { constructor(opts) { const pkgPath = pkgUp.sync(parentDir); - opts = Object.assign({projectName: require(pkgPath).name}, opts); + + opts = Object.assign({ + // if the package.json was not found, avoid breaking with `require(null)` + projectName: pkgPath && require(pkgPath).name + }, opts); if (!opts.projectName && !opts.cwd) { throw new Error('Project name could not be inferred. Please specify the `projectName` option.'); diff --git a/test.js b/test.js index 12f656b..5b9018e 100644 --- a/test.js +++ b/test.js @@ -2,6 +2,7 @@ import path from 'path'; import {serial as test} from 'ava'; import tempfile from 'tempfile'; import del from 'del'; +import pkgUp from 'pkg-up'; import Conf from './'; const fixture = '🦄'; @@ -161,3 +162,15 @@ test('`cwd` option overrides `projectName` option', t => { t.is(conf.get('foo'), fixture); del.sync(conf.path, {force: true}); }); + +test('safely handle missing `project.json`', t => { + const pkgUpSyncOrig = pkgUp.sync; + pkgUp.sync = () => null; + + let conf; + t.notThrows(() => { + conf = new Conf({projectName: 'conf-fixture-project-name'}); + }); + del.sync(conf.path, {force: true}); + pkgUp.sync = pkgUpSyncOrig; +});