I’m going to share my experience here but before I begin let me tell you why I found it very important to take advantage of TDD in your future projects, if you’re not using it already.
According to SOLID principle in software development, a class should have only a single responsibility (Single responsibility principle) which means you should be able to know what’s going to happen if you input a variable into the class. So I used to mock the data and pass the variable to the class to see if it returns what I expected to see but the issue with my old approach is that it only measures known variables and because you calculated it in your mind before hand and well quite often that turns out to be true.
So I really hope this would help you with your journey toward taking advantage of TDD in your applications. So lets begin. I’ve got to start with the fact that AngularJS, my preferred JS framework, is built with great testability features such as mocking server side request with ngMock module which fully utilizes server-side simulation. Moreover, dependency injection allows modules to be mocked and then tested as we go.
I personally prefer 3 magical combination of Angular modules, Karma and Jasmin. Karma is a node server environment which runs the tests of your application In its core by watching for changes in your testing and application files. when a unit test runs, Karma runs them in a browser of your choice and checks for mistakes. Jasmine is the most popular framework among Angular developers. Angular Mocks provides support to inject and mock AngularJS services into unit tests. We are going to need a test browser and I personally prefer to use PhantomJS but you can always use chrome or whatever.
We’ll get to build some basic unit tests for a controller and a service. So lets get to the business with downloading and installing necessary tools.
Lets install nodeJS first, here is a very convenient guide on how to install it :
if above link is not working just go to https://nodejs.org/en/ and click on download link.
and then install Karma:
npm install -g karma-cli
now it’s time to create a folder for your test app
C: mkdir TestApp cd TestApp
use following line to download necessary dependencies
npm init -f
now it’s time to add packages necessary for development of your unit tests. Please bear in mind that I only use bare minimum to just run a sample test case, of course your real-life project possibly involves much more packages and dependencies.
npm install angular --save-dev && npm install angular-mocks --save-dev && npm install karma --save-dev && npm install karma-jasmine --save-dev && npm install --save-dev karma-phantomjs-launcher
In the next post I’ll begin a sample app with some sample unit tests