Testing JavaScript with Jasmine — Basics

Benjamin Cunningham
letsboot
Published in
2 min readFeb 26, 2018

--

Testing your code is a very important asset to have for any project. That’s why in my nanodegree at Udacity, I have learnt to test my code and wanted to share with you my experience. Using an exercise given to me by Udacity, I had to implement code that tested code using Jasmine. Jasmine is a behavior-driven development framework for testing JavaScript code.

To test out Jasmine yourself, try using node.js, python or ruby, check out these tutorials. Test files are located in the Jasmine/spec folder once created and will analyze JavaScript files.

We will start by checking if Jasmine fails by changing the code. After that, I will show you some interesting code snippets.

Check out our Angular in-house trainings or a public Angular courses.
Try out fossilo.com, our angular project to archive complete websites.

In following video, I explain all tests that were needed for the project:

Jasmine Tests Explanations

First off, lets change the code in the spec file of feedreader.js:

With ‘expect(allFeeds.length).not.toBe(0);’ Jasmine is happy
Jasmine identifies there is an issue in the spec file.

In the following code, the ‘it’ function expects to test all feed URLs are defined and are longer that 0 characters located in the allFeeds array.

allFeeds variable array used to test code with Jasmine
A for loop is used to test all feeds

Below, the side menu is tested if it works when clicked on. It tests on the first click if the class of ‘menu-icon-link’ has a class of ‘menu-hidden’. if there is no ‘menu-hidden’ class on click, then it is false or correct. When clicked again, this time, there is a hidden menu and this concludes that the test is correct in both cases.

Test for side menu works on click events

Lastly, this beforeEach function makes sure that the ‘feed’ class is empty. then loads the first feed of 0. the entriesStart variable locates the URL in the feed. loadFeed loads the second feed and locates the URL thought he variable of entriesEnd. In the test function, both variables are tested to not be equal.

Determines if URLs of feed 1 and 2 are not equal

Jasmine has run all tests and returns green so all the tests have determined that the code is working correctly:

Jasmine has tested all specs and is happy

If you want to see the project yourself, feel free to clone it here. Testing might be a hassle to code, but it will help enormously to fix bugs and errors.

--

--

Benjamin Cunningham
letsboot

I live in Basel, CH and I aim to become a front end web developer. I have started working as a Co-Trainer and a Software Engineer at Letsboot.