Unit testing JavaScript with Jasmine

Share on facebook
Share on twitter
Share on linkedin

Hmm, JavaScript…it is that messy code which runs in the browser and contains a lot of $() function calls, right? NO. At least it shouldn’t be. JavaScript is a full featured language and all good development practices can be, and should be used in JavaScript development including but not limited to object oriented architecture, design patterns and automated tests (unit tests, integration tests).

In this article I’m going to show how to set up Jasmine for unit testing in JavaScript. To be more precise Jasmine is a behavior-driven development framework, not test driven development, but the essentials and the goal are the same: the more tests you have for your code the better.

Installation

Let’s see how to install and configure Jasmine:
Install with npm:

Initialize:

Set jasmine as your test script in your package.json:

Use npm to run the tests:

If you’d prefer to see the test results in the browser you can install the standalone version of the Jasmine, find the releases page here: https://github.com/jasmine/jasmine/releases.
Download the package, unzip, and add the following to the specs.html:

Writing the first test

Our first example test looks like this:

It seems like it doesn’t test anything, but if it runs successfully, it means you’ve configured Jasmine correctly. We can see three main parts of the above test:

  • The describe function groups related test cases into test suites.
  • The it function represents a test case.The description should describe the desired behaviour of the functionality to be tested.
  • The expect function contains the assertions for the test.

You can find more examples and detailed explanation on the Jasmine tutorials page here: https://jasmine.github.io/tutorials/your_first_suite

Quite easy, isn’t it? You might think writing tests is boring, time consuming and even not necessary. The deadlines are always tight, who has time to write tests? Yes, that is true, but having tests allows you to confidently make changes/refactor your code without breaking the existing functionality, and this can save you a lot of debugging time later.

In the upcoming blog posts I’ll show some tips and tricks about mocking input data for unit tests (especially for built in object like datetime or geolocation).

Agree? Disagree? Please let me know in the comments section below.

Subscribe to our newsletter

Be first to read new helpful post

Share this post with your friends

Share on linkedin
Share on xing
Share on twitter
Share on facebook

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
ProWeb365 Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
ProWeb365
Guest
ProWeb365

Awesome post. Thank you so much.