Skip to content

Instantly share code, notes, and snippets.

@the0neWhoKnocks
Created May 16, 2018 22:42
Show Gist options
  • Save the0neWhoKnocks/8a7a5437478f9a4554940c3447508257 to your computer and use it in GitHub Desktop.
Save the0neWhoKnocks/8a7a5437478f9a4554940c3447508257 to your computer and use it in GitHub Desktop.
Debugging Jest tests in a MonoRep with VSCode

Debugging Jest tests in a MonoRep with VSCode

If you're writing unit tests, there will be times when the ability to debug specific tests will come in handy. This is how you set up a debugging profile for VSCode.


Set up VSCode

At the root of your repo create a .vscode folder, and dump these files in it:

  • launch.json
  • debugJest.js
  • jestDebugger.js
#!/usr/bin/env node
/* eslint-disable no-console, import/no-dynamic-require */
const spawn = require('react-dev-utils/crossSpawn');
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', (err) => {
throw err;
});
const argv = process.argv.slice(2);
const nodeArgs = argv.slice(0, 1);
const jestArgs = argv.slice(1);
const result = spawn.sync(
'node',
nodeArgs
.concat(require.resolve(`${__dirname}/jestDebugger.js`))
.concat(jestArgs),
{ stdio: 'inherit' }
);
if (result.signal) {
if (result.signal === 'SIGKILL') {
console.log(
'The build failed because the process exited too early. ' +
'This probably means the system ran out of memory or someone called ' +
'`kill -9` on the process.'
);
} else if (result.signal === 'SIGTERM') {
console.log(
'The build failed because the process exited too early. ' +
'Someone might have called `kill` or `killall`, or the system could ' +
'be shutting down.'
);
}
process.exit(1);
}
process.exit(result.status);
/* eslint-disable no-console, import/no-dynamic-require */
const jest = require('jest');
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';
const argv = process.argv.slice(2);
const fileArgNdx = argv.length - 1;
const currPackage = argv[fileArgNdx].match(/.*\/packages\/[\w-]+\//)[0];
const jestConf = require(`${currPackage}/package.json`).jest;
const currTestFile = argv.pop().split(currPackage)[1];
jestConf.rootDir = currPackage;
jestConf.collectCoverage = false;
argv.push(
'--config',
JSON.stringify(jestConf),
currTestFile, // the last arg has to be the watched file
);
// @remove-on-eject-end
jest.run(argv);
{
"configurations": [
{
"name": "Debug Jest Tests",
"type": "node",
"request": "launch",
"runtimeExecutable": "${workspaceFolder}/.vscode/debugJest.js",
"args": [
"--runInBand",
"--no-cache",
"--env=jsdom",
"--watchAll",
"${file}",
],
"protocol": "inspector",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment