Since version 6, NPM has included a useful command for testing a library built locally from source code. It's called npm pack
and is a close cousin to gem build
in Ruby. You can see the command applied in practice in one of the projects I contributed to here. In this case, the result is installed by a Cypress Docker container for end-to-end testing.
Like gem build
, the command generates a single bundle file. It includes contents very similar to npm publish
. Unlike npm publish
, it places the bundle in the local file system instead of https://www.npmjs.com/ or some other online registry. This difference makes it great for testing the library manually and during CI to ensure it works as intended before being published.
The command is slower than npm link
, because running npm pack
and then npm install
is needed to test the package. From my experience, though, it's also free from all of its limitations. npm link
struggles even in mildly complicated projects. For example, it often incorrectly handles node_modules
dependencies between the linked package and the project linking it. On the whole, NPM is not great at handling symlinks which is what npm link
uses. And what's critical for the proper testing of NPM packages, is that the tests run in a production-like environment. npm pack
achieves this.
To be clear, npm pack
doesn't replace automated testing. Manual testing is rife with human errors and should be avoided. But it still has its uses. I already mentioned CI. Another example, is confirming bugs.
NPM libraries are used in a variety of situations and tech stacks. As an open source maintainer, you often get reports from developers using the package of issues not covered by automated tests. A quick way of confirming the issue exists, is to run npm pack
and run the package in an environment in which it supposedly fails. It's a good first step, possibly leading to fixing the issue and covering it with automated tests, so it doesn't happen in the future.