Skip to content

Instantly share code, notes, and snippets.

@alexanderankin
Created November 8, 2022 20:02
Show Gist options
  • Select an option

  • Save alexanderankin/9d5604d90da98dfc267d783ad08c64f0 to your computer and use it in GitHub Desktop.

Select an option

Save alexanderankin/9d5604d90da98dfc267d783ad08c64f0 to your computer and use it in GitHub Desktop.
How to disable tests on NPM

Skip tests on NPM

first, we will create a sample project:

mkdir ~/skip-tests-npm-demo
cd ~/skip-tests-npm-demo

then we will initialize the project:

cat > package.json <<EOF
{
  "name": "skip-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "deploy": "npm run test && echo deploying",
    "test": "echo 'test completed'"
  },
  "keywords": [],
  "license": "Apache-2.0"
}
EOF

we will note that there are two tasks, npm run deploy which depends on the NPM-standard test task finishing first (npm run test).

e.g.:

$ npm run test

> pj-test@1.0.0 test
> echo 'test completed'

test completed
$ npm run deploy

> pj-test@1.0.0 deploy
> npm run test && echo deploying


> pj-test@1.0.0 test
> echo 'test completed'

test completed
deploying

now, we would like to programatically skip, e.g. the test task, and simulate the event of it being successful (exiting with 0).

$ function skip_test_npm() { [ -f package.json ] || { echo no npm package found in this directory; return 1; }; local tempfile=package.json-skip-test-backup-$(date +%s); cp package.json $tempfile; jq '.scripts.test = "echo skipped"' package.json > package.json.tmp ; mv package.json{.tmp,}; npm "$@"; mv $tempfile package.json; }; skip_test_npm run deploy

> pj-test@1.0.0 deploy
> npm run test && echo deploying ; node deploy.js


> pj-test@1.0.0 test
> echo skipped

skipped
deploying
deployed
$ npm run deploy

> pj-test@1.0.0 deploy
> npm run test && echo deploying ; node deploy.js


> pj-test@1.0.0 test
> echo 'test completed'

test completed
deploying
deployed

the skip_test_npm script:

function skip_test_npm() {
    # ensure we are in a valid folder
    [ -f package.json ] || { echo no npm package found in this directory; return 1; };

    # create a temporary backup
    local tempfile=package.json-skip-test-backup-$(date +%s);
    cp package.json $tempfile;

    # edit package.json
    jq '.scripts.test = "echo skipped"' package.json > package.json.tmp ;
    mv package.json{.tmp,};

    # run npm with all the same arguments, except prefixed to a different directory
    npm "$@";

    # restore package.json
    mv $tempfile package.json;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment