DEV Community

loading...

Setting up a basic environment with Jasmine to test pure JavaScript logic

milantenk profile image Milán Tenk Updated on ・2 min read

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
Enter fullscreen mode Exit fullscreen mode

Install Jasmine:

npm install --save-dev jasmine
Enter fullscreen mode Exit fullscreen mode

Initiate Jasmine:

npx jasmine init
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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);
    });
});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

We can see the test case was executed successfully
image

Now the test runs let's see how the debugger can be used.

Put a breakpoint in the adder function:
image

Press F5 and choose JavaScript Debug Terminal
image

In the opened terminal run npm test and the breakpoint will be hit:
image

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.

Discussion (0)

pic
Editor guide