Saturday, June 29, 2013

Lesson 6: Angularjs Tutorial: Testing using ngMock $httpBackend and karma. Node REST testing with Mocha

In Lesson 5, we implemented a node REST server to perform CRUD operations for device data. We have not yet hooked our server to mongodb, we will do that once we completely understand and unit test existing code base. This is all about Testing, Testing & more Testing. Client side testing using Karma & Server Side Node.js REST API testing using Mocha

Our existing unit test cases handle static data being returned by the services. Since we have refactored our code to use $resource & $http, our unit test cases need to be refactored to utilize _$httpBackend_ which is a mock API provided by angularjs. Understanding $httpBackend takes a while and getting used to. The general steps in testing controllers using httpBackend are:

1. Inject _$httpBackend_
2. Use expectGet, expectPOST & expectPUT & respond API to implement mock backend behavior
3. Run methods under test & verify results
4. _$httpBackend_.flush() to flush pending requests on demand

Testing Controllers

Injecting _$httpBackend_ into the tests:


  it('listDeviceController check for devices in the model',
    inject(function(_$httpBackend_, $rootScope, $controller, Devices) {
        var scope = $rootScope.$new();
        var mockBackend = _$httpBackend_;

Implementing Mock Backend behavior:


        mockBackend.expectGET('http://localhost:3000/devices').
          respond([{id:0, name: "iphone", assetTag:"a23456", owner:"dev", desc:"iOS4.2"}]);

expectGET specifies the request expectation & respond implements the mock response

Run methods under test 

 controllerSpec.js: var ctrl = $controller('deviceListController', {$scope: scope}, Devices);

This creates the deviceListController. In the controller the following statement "$scope.devices = Devices.query()" does a query using the Devices service. Essentially, it makes a http GET request. This is intercepted by the ngMock angularjs module & its response is provided to the controller. 

Flush the response manually

        mockBackend.flush();  

Test the conditions

        expect(scope.devices).toEqualData([{id:0, name: "iphone", assetTag:"a23456", owner:"dev", desc:"iOS4.2"}]);

Here is the code for controller CRUD testing with ngMock httpBackend:
--
--

Testing Services

Testing services is fairly straightforward. We are mainly ensuring that the services send the right http requests to the backend & expect the right responses. 

--
--

Trouble-shooting:


Error: Unknown provider: $resourceProvider <- devices="" div="" resource="">

  ngResource is not part of angularjs core. So, you have to include it specifically in your test specs, like so: 

describe('service', function() {
  beforeEach(function(){
    module('cotd.services');
    module('ngResource');
  });

Testing the server - Node REST service testing using Mocha, Chai & supertest

Now that we have extensively implemented client side unit testing specs, the focus naturally turns to testing the server side. After reviewing a bunch of server side testing frameworks, i think Mocha provides for a better suite since it allows for BDD a.k.a jasmine style syntax. This allows us to keep the testing constructs fairly consistent between client & server. Lets implement hands on mocha testing for our server.

We can accomplish Server side REST based testing easily by combining 3 frameworks Mocha, Chai & SuperTest. They play well nicely and makes it easier to write Node Based REST tests. 

Step 1: is to add mocha, Chai & supertest to package.json
{
  "name": "cotd-server",
  "description": "cotd backend",
  "version": "0.0.1",
  "private": "true",
  "dependencies": {
    "express": "3.2.2",
    "cors": "*"
  },
  "devDependencies":{
    "mocha": "*",
    "chai": "*",
    "supertest": "*"
  },
  "scripts":{
     "test": "mocha"
  }
}

Step 2: export the express app as a module in server.js. This is for Mocha to test the server functionality without running the server first.

module.exports = app; 

Step 3: create a test directory in your server folder and Create a new file for the test spec called test-devicesRest.js. Require mocha, chai & supertest in your test spec.

var chai = require('chai'),
    express = require('express'),
    request = require('supertest');

var app = require('../server');

var expect = chai.expect;

Step 4: writing a GET test

describe('GET /devices', function(){
    it('should return 200 and JSON with valid keys', function(done){
        request(app)
        .get('/devices')
        .end(function(err, res){
            //validate the keys in the response JSON matches, we dont care about the values
            expect(res.status).to.equal(200);
            expect(res.body[0]).to.have.keys(['id', 'name', 'assetTag', 'owner', 'desc']);
            done();
        });
    });  
});

Step 5: creating a simple Makefile to run our test using Mocha. running make test on the command line should run mocha. It looks for the test directory and executes test specs within it.

REPORTER = list
#REPORTER = dot

test:
@./node_modules/.bin/mocha \
--reporter $(REPORTER)

test-w:
@./node_modules/.bin/mocha \
--reporter $(REPORTER) \
--growl \
--watch


.PHONY: test

Step 6: Write other tests. Here is a complete source code for our REST tests
--

--

git tag

git checkout v1.6


46 comments:

David said...

I like this ! Any chance you'll be posting a part 7 ?

angularjs training in hyderabad said...

In addition to learning angularjs at online Angularjs training, this blog adds to my learning platforms. Great work done by the website owner. Thanks for your in depth research and experience sharing on this website.

Unknown said...

Pretty post, I hope your site useful for many users who want to learn basics of programming to enhance their skill for getting good career in IT, thanks for taking time to discuss about fundamental programming niche.
With Regards,
Angularjs training in chennai|Angularjs course in chennai

Unknown said...


The oracle database is capable of storing the data in two forms such as logically in the form of table spaces and physically like data files.
Oracle Training in Chennai | oracle dba training in chennai

geethu said...

Angularjs is the great javascript framework that has some compelling features not for developers but also for the designers. Angularjs is very essential for the web developers to know about its importance.
Angularjs Training in Chennai | angularjs course in chennai

Unknown said...

One of the reasons for AngularJS’ success is its outstanding ability to be tested. It’s strongly supported by Karma (the spectacular test runner written by Vojta Jína) and its multiple plugins. Karma, combined with its fellows Mocha, Chai and Sinon, offers a complete toolset to produce quality code that is easy to maintain, bug-free and well documented.

AngularJS Training in Chennai
AngularJS Training Institute in Chennai

DBA training courses said...

You have shared informative details with me. Keep updating.
DBA course syllabus | Oracle dba course

Unknown said...

Well written,...... Thanks for sharing.....
angularjs training course in chennai

pooja said...

It seems you are so busy in last month. The detail you shared about your work and it is really impressive that's why i am waiting for your post because i get the new ideas over here and you really write so well.


MEAN stack training in Chennai

MEAN stack training in bangalore

MEAN stack training in tambaram

MEAN stack training in annanagar

MEAN stack training in Velachery

MEAN stack training Sholinganallur

gowsalya said...

The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
Devops Training in pune|Devops training in tambaram|Devops training in velachery|Devops training in annanagar
DevOps online Training

Mounika said...

Your story is truly inspirational and I have learned a lot from your blog. Much appreciated.
python training institute in chennai
python training in velachery
python training institute in chennai

Unknown said...

Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

Data Science training in Chennai
Data science training in bangalore
Data science training in pune
Data science online training

Anonymous said...

I really like your blog. You make it interesting to read and entertaining at the same time. I cant wait to read more from you.
angularjs-Training in pune

angularjs-Training in chennai

angularjs Training in chennai

angularjs-Training in tambaram

angularjs-Training in sholinganallur

Tejuteju said...

It is nice blog Thank you provide important information and I am searching for the same information to save my time AngularJS Online Training India

Aaditya said...

It’s very informative and helpful, Thank you for sharing this wonderful post.


ExcelR Data Science

zaintech99 said...

It should be noted that whilst ordering papers for sale at paper writing service, you can get unkind attitude. In case you feel that the bureau is trying to cheat you, don't buy term paper from it.
ExcelR Data science courses in Bangalore

malaysiaexcelr01 said...




Really appreciate this wonderful post that you have provided for us.Great site and a great topic as well i really get amazed to read this. Its really good.






data science course malaysia

janitha said...

Thanks for your post. I’ve been thinking about writing a very comparable post over the last couple of weeks, I’ll probably keep it short and sweet and link to this instead if thats cool. Thanks.
big data course malaysia

Bushraah88 said...

I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.
Great, Keep it up and Thanks for sharing.

jaanu said...

Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!
data science course malaysia

jaanu said...

After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.
data science course malaysia

Manipriyan said...
This comment has been removed by the author.
nash b said...

Nice Post..
final year project proposal for information technology

free internship for bca

web designing training in chennai

internship in coimbatore for ece

machine learning internship in chennai

6 months training with stipend in chennai

final year project for it

inplant training in chennai for ece students

industrial training report for electronics and communication

inplant training certificate

Softgen Infotech said...

Such great information for blogger iam a professional blogger thanks…

Looking for Data Warehousing Training in Bangalore, learn from Softgen Infotech provide Data Warehousing Training on online training and classroom training. Join today!

Reshma said...

Wonderful blog. It is really informative to all.keep update more information about this
Tally Course in Chennai
Tally Course in Hyderabad
Tally training coimbatore
Tally Course in Coimbatore
Tally course in madurai
Tally Training in Chennai
Tally Institute in Chennai
Tally Training Institute in Chennai
Selenium Training in Bangalore
Ethical hacking course in bangalore

raju said...

nice...
inplant training in chennai
inplant training in chennai for it
panama web hosting
syria hosting
services hosting
afghanistan shared web hosting
andorra web hosting
belarus web hosting
brunei darussalam hosting
inplant training in chennai

dras said...

very nice post...
inplant training in chennai
inplant training in chennai
inplant training in chennai for it
Australia hosting
mexico web hosting
moldova web hosting
albania web hosting
andorra hosting
australia web hosting
denmark web hosting

shree said...

very nice....
inplant training in chennai for it
namibia web hosting
norway web hosting
rwanda web hosting
spain hosting
turkey web hosting
venezuela hosting
vietnam shared web hosting

tech bosa said...

You ought to be a part of a contest for one of the most useful sites on the internet. I most certainly will highly recommend this website!

Priyanka said...

Attend The Course in Data Analytics From ExcelR. Practical Course in Data Analytics Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Course in Data Analytics.
Course in Data Analytics
Data Science Interview Questions

nisha said...

Great Blog. The Blog is easily understand for the Learners.

Data Science Training Course In Chennai | Data Science Training Course In Anna Nagar | Data Science Training Course In OMR | Data Science Training Course In Porur | Data Science Training Course In Tambaram | Data Science Training Course In Velachery

sushmi reddy said...

I like this one...more helpful information provided here.I am quite sure I will learn much new stuff right here! Good luck for the next!
Oracle Training | Online Course | Certification in chennai | Oracle Training | Online Course | Certification in bangalore | Oracle Training | Online Course | Certification in hyderabad | Oracle Training | Online Course | Certification in pune | Oracle Training | Online Course | Certification in coimbatore

Anonymous said...

SSC Result 2020 Published Date & Time by ssc result
ssc result 2020
Education Board of Bangladesh.
Many of You Search For SSC Result Kobe Dibe on Internet
as Well as Facebook. The results of Secondary School Certificate
(SSC)—and its equivalent examinations—for 2020 have been published.
SSC & Dakhil Result 2020 Published Date is Very Important For T
he Students Who Attend The SSC Exam 2020.

ravali said...

Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!

Simple Linear Regression

rocky said...

I'm very impressed your article. I like that your article.
Python Training in Chennai

Python Training in Bangalore

Python Training in Hyderabad

Python Training in Coimbatore

Python Training

python online training

python flask training

python flask online training


devi said...

Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well. Data Science Training In Chennai | Certification | Data Science Courses in Chennai | Data Science Training In Bangalore | Certification | Data Science Courses in Bangalore | Data Science Training In Hyderabad | Certification | Data Science Courses in hyderabad | Data Science Training In Coimbatore | Certification | Data Science Courses in Coimbatore | Data Science Training | Certification | Data Science Online Training Course

shankarjaya said...

It is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot
Salesforce Training in Chennai

Salesforce Online Training in Chennai

Salesforce Training in Bangalore

Salesforce Training in Hyderabad

Salesforce training in ameerpet

Salesforce Training in Pune

Salesforce Online Training

Salesforce Training

All New Result said...

National University is published the nu honours 4th year exam result 2021 on online. Students now can check the result from nu.ac.bd/results as well as examresulthub.com

Unknown said...

Hi! I simply need to offer you a major approval for your incredible data you have here on this post. I'll be returning to your site for all the more soon.
best interiors

jobnewsbd24.com said...

GST Primary Selection Result has been publihsed very update from their official website otherwise visit to our website to seeGuccho Primary Selection Result our website available

Varunsharma said...

Cyber Security Course in Mumbai
Cyber Security Course in Ahmedabad
Cyber Security Course in Kochi
Cyber Security Course in Trivandrum
Cyber Security Course in Kolkata
The Growing Imporance of Cyber Security Analytics

Reshma said...

This post is so interactive and informative.keep update more information...
Artificial Intelligence Course in Bangalore
Artificial Intelligence course in Pune
Artificial Intelligence Course in Gurgaon
Artificial Intelligence Course in Hyderabad
Artificial Intelligence Course in Delhi

traininginstitute said...

Your work is very good and I appreciate you and hopping for some more informative posts.
data scientist course

Unknown said...

This is a fabulous post I seen because of offer it. It is really what I expected to see trust in future you will continue in sharing such a mind boggling post data scientist course in surat

teenooth said...

s2u32u4r25 o5g63y6h72 r4d70p2o84 j7z19s7x69 s1y56c7j99 f9l48o3s16

Anonymous said...

hermes bag outlet
jordan shoes
bape
off white
off white hoodie