From 277014d4e550a499d8e3b361fd81b39010298bda Mon Sep 17 00:00:00 2001 From: "Kent C. Dodds" Date: Wed, 8 Feb 2017 10:56:30 -0700 Subject: [PATCH] fix(init): don't fail when there are no scripts **What**: Closes #89 **Why**: Because we want to be able to init even if you have no `scripts` in your `package.json` **How**: ES6 magic --- .../fixtures/_package-no-scripts.json | 1 + src/bin-utils/initialize/index.js | 2 +- src/bin-utils/initialize/index.test.js | 23 +++++++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 src/bin-utils/initialize/fixtures/_package-no-scripts.json diff --git a/src/bin-utils/initialize/fixtures/_package-no-scripts.json b/src/bin-utils/initialize/fixtures/_package-no-scripts.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/src/bin-utils/initialize/fixtures/_package-no-scripts.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/src/bin-utils/initialize/index.js b/src/bin-utils/initialize/index.js index 1101f77..ad9782a 100644 --- a/src/bin-utils/initialize/index.js +++ b/src/bin-utils/initialize/index.js @@ -10,7 +10,7 @@ function initialize(configType = 'js') { /* eslint global-require:0,import/no-dynamic-require:0 */ const packageJsonPath = findUpSync('package.json') const packageJson = require(packageJsonPath) - const {scripts} = packageJson + const {scripts = {}} = packageJson packageJson.scripts = { start: 'nps', test: scripts.test ? 'nps test' : undefined, diff --git a/src/bin-utils/initialize/index.test.js b/src/bin-utils/initialize/index.test.js index 355d641..b9e9308 100644 --- a/src/bin-utils/initialize/index.test.js +++ b/src/bin-utils/initialize/index.test.js @@ -89,3 +89,26 @@ test('initialize without a test script should not add a test to the package.json start: 'nps', }) }) + +test('initialize without any scripts should successfully create an empty package-scripts.js file', () => { + const packageJsonDestination = resolve('./src/bin-utils/initialize/fixtures/_package-no-scripts.json') + const mockWriteFileSync = spy() + const mockFindUpSync = spy(file => { + if (file === 'package.json') { + return packageJsonDestination + } + throw new Error('Should not look for anything but package.json') + }) + jest.resetModules() + jest.mock('find-up', () => ({sync: mockFindUpSync})) + jest.mock('fs', () => ({writeFileSync: mockWriteFileSync})) + const initialize = require('./index').default + + initialize() + const [, packageJsonStringResult] = mockWriteFileSync.firstCall.args + const {scripts: packageJsonScripts} = JSON.parse(packageJsonStringResult) + + expect(packageJsonScripts).toEqual({ + start: 'nps', + }) +})