Search code examples
node.jsnpmspawn

Node.js unit test spawn command to view npm package details


I'm creating a function that gets the tarball uri of a package name. It works, but the problem is how can automate tests for it? Do I somehow mock the command line or somehow mock the npm registry? I'm not sure what the protocol is that npm uses.

const spawn = require('child_process').spawn;

let url = spawn('npm', ['view', 'express', 'dist.tarball']);

url.stdout.on('data', data => {
  console.log(data.toString());
});

url.stderr.on('data', data => {
  console.log(data.toString());
});

//should be 0 if all OK
url.on('close', code => {
  if (code) {
    console.log('process failed');
  }
});

Solution

  • Ok, used a combination of rewire and mock-spawn.