Debug node.js with VS Code

Set up VS Code to debug node.js

🚗 1. Add js files

1
2
3
4
// main.js
const { add } = require('./calc');

console.log(add(3, 4));
1
2
3
4
5
6
// calc.js
const add = (num1, num2) => {
return num1 + num2;
};

module.exports.add = add;

🚗 2. Create a launch.jsonfile

🚗 3. Edit launch.json to set the entry point

In this case, main.js is the entry point.

🚗 4. Set breakpoint and Run

Yay! easy ✨

💰💰💰 Bonus! - test with Jest 💰💰💰

🚙 1. Initialise npm

1
npm init -y

🚙 2. Install Jest

1
npm install --save-dev jest

🚙 3. Add test sctipt to package.json

1
2
3
"scripts": {
"test": "jest --watchAll"
}

🚙 4. Create test file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//calc.spec.js
const { add } = require('./calc');

describe('calc', () => {
describe('add', () => {
it('Should add two numbers', () => {
// Arrange
const expected = 7;

// Act
const result = add(3, 4);

// Assert
expect(result).toBe(expected);
});
});
});

🚙 5. Run test

1
npm test

Yay! Easy as 🎉🎉🎉