In a lot of use cases, Jasmine is used together with test runners like Karma. However, if we do not want to run the JavaScript code in a browser, but only using Node, then Karma is not necessary.
In this case, we can use Jasmine directly and in this post, I'm going to describe, how can we do that and how can we use breakpoints in Visual Studio Code in it.
This project setup can be useful for example in those cases, when we are practicing for interviews, coding competitions, or when we take out a code part from a legacy system to check some edge cases with tests on them.
So let's get started.
As a prerequisite make sure that Node.js is installed on the machine.
Initialize a package.json
:
npm init -y
Install Jasmine:
npm install --save-dev jasmine
Initiate Jasmine:
npx jasmine init
This will generate the spec
folder and a default jasmine config in spec/support
.
In package.json
update the test
npm script to
"scripts": {
"test": "jasmine"
}
Create the src
folder and put a file in it with simple logic. For example, I create the adder.js
which looks like this:
function adder(a, b) {
return a + b;
}
module.exports = adder;
To write a test for it create the adder.spec.js
file in the spec
folder with the following content:
const adder = require('../src/adder');
describe("adder", () => {
it("should add the values", () => {
// ARRANGE & ACT & ASSERT
expect(adder(1, 2)).toEqual(3);
});
});
Note that based on the default configuration of Jasmine only test files in the spec
folder will be detected with the *.[sS]pec.js
ending.
And run the Jasmine test with the following command
npm test
We can see the test case was executed successfully
Now the test runs let's see how the debugger can be used.
Put a breakpoint in the adder
function:
Press F5
and choose JavaScript Debug Terminal
In the opened terminal run npm test
and the breakpoint will be hit:
And that's it. If you don't want to go through the steps, the environment can be found on GitHub here.
Note that in this case, Jasmine works with Node. It does not support using the ES6 module imports out of the box. It follows that the require
module syntax can only be applied.
Top comments (0)