Hmm, JavaScript…it is that messy code that 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:
npm install --save-dev jasmine
Initialize:
node node_modules/jasmine/bin/jasmine init
Set jasmine as your test script in your package.json:
"scripts": { "test": "jasmine" }
Use npm to run the tests:
npm test
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:
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 behavior of the functionality to be tested.
The expected function contains the assertions for the test.
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 a built-in objects like DateTime or geolocation).
Agree? Disagree? Please let me know in the comments section below.