If I'm not mistaken, one good reason to use test scripts is to prevent releasing buggy code. So I wrote my own test script which throws an error if one of the test cases fails.
// index.test.js
if (!testCase) {
throw new Error("Error detected, publishing process supposed to be canceled!");
}
// package.json
"scripts": {
"test": "node index.test.js",
"prepublishOnly": "npm test"
},
Now when I run npm publish
my test script gets executed as intended, throws an error but my npm package gets published nonetheless.
I imagine that using a testing framework such as Mocha or Jest, might solve the problem but I would prefer to do it in plain node.js!
Thx for your comment @tkausl!
I'd assume, even though an exception is thrown, the node process doesn't exit with an error code, which makes npm think everything went well. You need to make sure to exit with an error code. –
Using process.exit(1)
instead of throw new Error()
indeed solves the problem!