I am building a cross-platform node utility to read the filesystem (devices, partitions) details, and in my tests I need to test the behaviour when an error is thrown from the shelled commands that the utility runs to obtain its data.
Unfortunately I have very little knowledge of dos or PowerShell and I do not know how to write a batch command that throws an error and exits with an error.
How can I throw an error in batch so that the child process can catch it?
Here's example code for you to fiddle with:
import os from 'os';
import child from 'child_process';
import { expect } from 'chai';
const cmd = os.platform() === 'win32'
// This command should result in throwing an error to exec
? `1>&2 echo 'Echoed Error'\nexit /b 1`
// This has the expected behaviour on linux and osx
: `>&2 echo 'Echoed Error'; exit 1`;
expect(child.execSync.bind(child, cmd)).to.throw();
child.exec(cmd, (err) => {
expect(err).to.be.an.instanceof(Error);
});
I found a way to cause an error in the cmd, which is to call a non-existing external or internal command. Hence a command like error
or iamnotanexistingcommand
will throw an error, which is sufficient for what I am trying to reproduce.