Jasmine Framework Tutorial: Unit Testing with Example

โšก Smart Summary

Jasmine is the behavior-driven JavaScript testing framework that runs Node.js unit tests without a browser or DOM, using describe blocks, it specs and expect matchers to verify that every exported function behaves as documented.

  • ๐Ÿ”˜ Framework role: Jasmine tests any JavaScript without browsers, DOM or helper libraries.
  • โ˜‘๏ธ Environment setup: Install the module, run jasmine init, then inspect spec/support/jasmine.json.
  • โœ… Spec pattern: describe names a suite, it defines a spec, expect asserts the result.
  • ๐Ÿงช Matchers: toBe, toEqual, toContain, toThrow and toHaveBeenCalled cover most assertions.
  • ๐Ÿ› ๏ธ Modern runner: The maintained jasmine package replaces the unmaintained jasmine-node module.
  • ๐Ÿ“Š Framework choice: Jasmine ships assertions and spies, while Jest adds parallel runs and snapshots.

Jasmine framework tutorial for unit testing Node.js applications

What is JasmineJS?

Jasmine is an open-source and most popular JavaScript library testing framework to test any kind of JavaScript application. Jasmine follows Behavior Driven Development (BDD) procedure to ensure that each line of JavaScript statement is properly unit tested.

What is the Jasmine Framework Used for?

Testing is a key element to any application. For Node.js unit testing, the framework available for testing is called Jasmine. In early 2000, there was a framework for testing JavaScript applications called JsUnit. Later this framework got upgraded and is now known as Jasmine.

Jasmine helps in automated Unit Testing, something which has become quite a key practice when developing and deploying modern-day web applications.

In this Jasmine tutorial, you will learn how to get your environment setup with Jasmine and how to run Jasmine tests for your first Node.js application.

Jasmine for testing Node.js applications

Jasmine is a Behavior Driven Development(BDD) testing framework for JavaScript. It does not rely on browsers, DOM, or any JavaScript framework. Thus, itโ€™s suited for websites, Node.js projects, or anywhere that JavaScript can run. To start using Jasmine, you need to first download and install the necessary Jasmine modules.

How to Setup Jasmine Test Environment

Next in this Jasmine Node.js tutorial, you would need to initialize your environment and inspect the Jasmine configuration file. The below steps show how to setup Jasmine in your environment

Step 1) Install NPM Modules
You need to Install NPM jasmine module to use the Jasmine framework from within a Node application. To install the jasmine-node module, run the below command.

npm install jasmine-node

Version note (2026): the historical command above still works, but the jasmine-node module is in maintenance mode and bundles Jasmine 1.3, so keep it only for legacy projects. New Node.js work installs the maintained Jasmine CLI as a dev dependency and calls it through npx:

npm install --save-dev jasmine
npx jasmine init

Jasmine 6.x is the current major line and supports Node.js 20, 22 and 24, and Node.js 24 is the Active LTS release in 2026.

Step 2) Initialize the Jasmine Environment
Initializing the project โ€“ By doing this, Jasmine creates a spec directory and configuration json for you. The spec directory is used to store all your test files. By doing this, Jasmine will know where all your tests are, and then can execute them accordingly. The JSON file is used to store specific configuration information about Jasmine.

To initialize the Jasmine environment, run the below command

jasmine init

Step 3) Inspect your configuration file.
The configuration file will be stored in the spec/support folder as jasmine.json. This file enumerates the source files and spec files you would like the Jasmine runner to include.

The below screenshot shows a typical example of the jasmine.json file for Jasmine.

Jasmine configuration file in spec support folder showing spec directory and spec_files

  1. Note that the spec directory is specified here. As noted earlier, when jasmine runs, it searches for all tests in this directory.
  2. The next thing to note is the spec_files parameter โ€“ This denotes that whatever test files are created they should be appended with the โ€˜specโ€™ keyword.

Configuration note: in Jasmine 6.x the same file also accepts helpers, which load once before every spec, and an env block holding options such as random and stopSpecOnExpectationFailure. The default spec_files glob is **/*[sS]pec.?(m)js, and a different file can be passed with –config or the JASMINE_CONFIG_PATH variable.

Next in this Jasmine framework tutorial, we will learn how to use Jasmine to test Node.js applications.

How to use Jasmine to test Node.js applications

In order to use Jasmine unit testing for Node.js applications, a series of steps need to be followed.

In our example below, we are going to define a module which adds 2 numbers which need to be tested. We will then define a separate code file with the test code and then use Jasmine to test the Add function accordingly.

Step 1) Define the code which needs to be tested. We are going to define a function which will add 2 numbers and return the result. This code is going to be written in a file called โ€œAdd.js.โ€

The screenshot below shows the finished Add.js module, and the same code is repeated as text underneath it.

Add.js module exporting the AddNumber function that returns the sum of two parameters

var exports=module.exports={};
exports.AddNumber=function(a,b)
{
return a+b;
};

Code Explanation

  1. The โ€œexportsโ€ keyword is used to ensure that the functionality defined in this file can actually be accessed by other files.
  2. We are then defining a function called โ€˜AddNumber.โ€™ This function is defined to take 2 parameters, a and b. The function is added to the module โ€œexportsโ€ to make the function as a public function that can be accessed by other application modules.
  3. We are finally making our function return the added value of the parameters.

Step 2) Next, we need to define our Jasmine test code, which will be used to test our โ€œAddโ€ function in the Add.js file. The below code needs to be put in a file called add-spec.js.

Note: The word โ€˜specโ€™ needs to be added to the test file so that it can be detected by Jasmine.

The screenshot below shows the same spec file open in an editor.

add-spec.js file with a describe suite and an it spec asserting AddNumber returns 11

var app=require("../Add.js");
describe("Addition",function(){
it("The function should add 2 numbers",function() {
var value=app.AddNumber(5,6);
expect(value).toBe(11);
});
});

Code Explanation

  1. We need to first include our Add.js file so that we can test the โ€˜AddNumberโ€™ function in this file.
  2. We are now creating our test module. The first part of the test module is to describe a method which basically gives a name for our test. In this case, the name of our test is โ€œAdditionโ€.
  3. The next bit is to give a description for our test using the โ€˜itโ€™ method.
  4. We now invoke our AddNumber method and send in 2 parameters 5 and 6. This will be passed to our AddNumber method in the Add.js file. The return value is then stored in a variable called value.
  5. The final step is to do the comparison or our actual test. Since we expect the value returned by the AddNumber function to be 11, we define this using the method expect(value).toBe(the expected value).

Output

  1. In order to run the test, one needs to run the command jasmine.
  2. The below screenshot shows that after the jasmine command is run, it will detect that there is a test called add-spec.js and execute that test accordingly. If there are any errors in the test, it will be shown accordingly.

Console output of the jasmine command reporting the executed add-spec test

The Add example uses a single matcher, yet Jasmine ships a full set of them. The table below lists the ones that cover almost every assertion you will write.

Jasmine Matchers You Will Use Most

A matcher is the comparison that follows expect(). Chain .not before any matcher to invert it, as in expect(value).not.toBe(11).

Matcher What it checks Typical use
toBe Strict identity, the same comparison as === expect(value).toBe(11)
toEqual Deep equality of objects and arrays expect(user).toEqual({id: 1})
toContain Membership inside an array or a string expect(files).toContain(โ€˜add-spec.jsโ€™)
toBeDefined The value is not undefined expect(app.AddNumber).toBeDefined()
toThrow The wrapped function raises an error expect(callAdd).toThrow()
toHaveBeenCalled A spy was invoked at least once expect(logger.write).toHaveBeenCalled()

Two habits keep failures readable. Use toBe only for primitives and identical references, because two objects with the same contents are never ===. Use toEqual for structures, and add toHaveBeenCalledWith when the arguments matter as much as the call itself.

Setup, Teardown, and Spies in Jasmine

Real suites need shared state and doubles for slow collaborators. Jasmine supplies both without any extra package.

  • beforeEach and afterEach run before and after every spec inside a describe block, which is the natural place to rebuild fixtures.
  • beforeAll and afterAll run once for the whole block, so reserve them for expensive work such as opening a connection.
  • spyOn(object, โ€˜methodโ€™) replaces a real method with a tracking double; add .and.returnValue() to control what it answers.
  • jasmine.createSpy(โ€˜nameโ€™) builds a standalone double for a callback that has no object to attach to.
  • Asynchronous specs may be declared async and awaited, may return a promise, or may accept a done callback that must be called exactly once.

Spies reset between specs, so a suite never leaks a stubbed method into the next test. That isolation is what makes a failing spec point at one defect instead of a chain of them, which is the same discipline described in the unit testing fundamentals.

Jasmine vs Mocha vs Jest

Jasmine is one of three frameworks that dominate JavaScript testing, and the choice usually comes down to how much wiring you want to own.

Aspect Jasmine Mocha Jest
Assertions Built in Added, usually Chai Built in
Spies and mocks Built in Added, usually Sinon Built in
Execution Serial Serial Parallel across processes
Snapshots No No Yes
Common home Angular, plain Node.js Flexible Node.js stacks React and modern bundlers

Pick Mocha when you want to assemble your own assertion and mocking stack, and Jest when parallel runs, coverage and snapshots matter more than configuration control. Jasmine remains the lightest option that still arrives complete, which is why it stays common in automation testing suites.

FAQs

Jasmine reads spec_dir as a prefix, then every glob listed in spec_files, so only matching files run. Paths beginning with an exclamation mark are excluded, and helpers load once before the specs to register shared setup.

Declare the spec async and await the call, return a promise, or accept a done callback. The async guide warns that done must fire exactly once, otherwise failures land on the wrong spec.

Pass a path or glob after the runner, for example npx jasmine spec/appSpec.js. The –filter flag accepts a pattern matched against the describe name, which keeps feedback fast while you work on a single suite.

The jasmine-node package sits in maintenance mode, still bundles Jasmine 1.3, and lists Node.js 10 and 12 as current. The official jasmine package tracks the framework and supported Node.js releases instead.

Prefix a spec with x, as in xit or xdescribe, and Jasmine reports it as pending. Prefix it with f, as in fit or fdescribe, and only the focused specs run. Remove both prefixes before committing.

AI assistants draft describe blocks, matchers and edge cases from an existing module in seconds, and they flag suites that fail intermittently. Every generated spec still needs review, because a confident assertion about wrong behaviour hides the defect.

GitHub Copilot completes spec bodies as you type and its agent mode can open a pull request that repairs broken specs after a refactor. Treat the diff as a proposal and run the suite yourself.

Angular still scaffolds Jasmine specs, and Protractor used Jasmine as its default framework before it was archived. Teams now pair Jasmine with Karma for browsers, or move browser flows to Cypress and Playwright.

Summarize this post with: