© 2014, Glarimy. All rights reserved. G l a r i m y.

22
G l a r I m y Presentation on Testing AngularJS with Jasmine & Karma Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat http://www.glarimy.com | @glarimy | [email protected] version 1.0 | 29 October 2014 © 2014, Glarimy. All rights reserved. http://www.glarimy.com G l a r i m y

Transcript of © 2014, Glarimy. All rights reserved. G l a r i m y.

G l a r I m y Presentation on

Testing AngularJS with

Jasmine & KarmaKrishna Mohan Koyya

Proprietor & Principle ConsultantGlarimy Technology Services | Benguluru | Bharat

http://www.glarimy.com | @glarimy | [email protected] version 1.0 | 29 October 2014

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

G l a r i m y

The Classroom Protocol• Few Administrative Formalities

– Sign in the attendance sheet, if provided– Fill-in the feedback at the end of sessions, if provided

• Derive Maximum Value– Ask questions, any time– Participate in discussions and lab exercises– Avoid brining personal or office work to the class room– Stay away from internet while class in the session

• Lets Learn Together– Switch-off or mute personal phones– Leave/enter the class room without disturbing the class– Take phone calls outside the class room– Keep the class room clean and professional– No cross discussions

• Reference Material– Download from http://www.glarimy.com – No Print/CD. Protect Environment

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com.

Glarimy Technology Services• About Glarimy

– Established in 2008 and Registered in 2010– Based out of Benguluru, Bharat (Bangalore, India)– http://www.glarimy.com

• Business Interests– Technology Consulting

• Architectural Appreciation and Review• Prototyping

– Corporate Training• Software Design, Architecture and Processes• Web 2.0 Technologies• Standard and Enterprise Technologies

– Weekend Public Workshops• One-day Executive Workshops on Saturdays

• Business Reach– Geographies: Banguluru, Chennai, Pune, Hyderabad, Kochi and etc., – Client Base: Sharp, GlobalDoc and LamResearch– Partner Clients: Robert Bosch, Samsung, Cisco, Vmware and etc.,

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Krishna Mohan Koyya• Career spanning across 17 years

– 9 Years into Software Engineering with Cisco Systems, Wipro/Lucent and HP– 6 Years as Principle Consultant and Founder of Glarimy Technology Services– 1 Year as CEO at Sudhari IT Solutions, Bangalore– 1 Year as HoD at Sasi Institute of Technology and Engineering, Tadepalligudem,

Andhra Pradesh

• Proven Delivery– Web 2.0: ExtJS, Dojo, Jquery Frameworks, AngularJS, HTML5, CSS3, XML– Enterprise Java: Spring, Hibernate, EJB, JSF, OSGi, Web Services, xUNIT family– Design Patterns, Architectural Patterns, TDD

• Technology Expertise– Distributed Systems and Network Management Systems– Object Oriented Systems Development– Infrastructure, Middleware and Web Layers with Java and Javascript

• Academics– M.Tech (Computer Science & Tech) from Andhra University, Visakhapatnam– BE (Electronics & Comm. Engg) from SRKR Engg. College, Bhimavaram

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

The Environment• Testing and AngularJS

– AngularJS is built on the concepts of Dependency Injection and Single Responsibility

– Naturally, this approach makes it testable

• Test Specifications with Jasmine– Jasmine is one of the popular test frameworks for JavaScript applications– Same can be used for AngularJS as well– Jasmine offers rich set of matchers (for assertions) and spies (for mocking)

• Running the tests using Karma– Karma is one of the popular test runners– Developed by Google and recommended for AngularJS– Can run the Jasmine test specifications– Can be integrated with many other eco-system frameworks of AngularJS– Distributed as a NodeJS package

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

The Environment

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

J asmine

Karma

NodeJS

Package Karma CLI

Test Specification

Expectation

runs

*

Test Framework

Test Runnerhosts and executes

is a

is a

to be installed on to be installed on

npmis used to install

*

End User (Tester)

installs packages using

runs karma using

develops

*

is a collection of*

Matcher

offers *

Spy

*

is written using

Testing AngularJS Using Jasmine and Karma@2014, Glarimy | www.glarimy.com | [email protected]

Setting-up the Environment• Install NodeJS

– Download it from http://nodejs.org/download/– Run the installer (available for Windows and Mac) – Setup the distributes (on Ubuntu and etc.,)

• Install Node Package Manager (npm)– Comes with NodeJS, by default– Command line tool to manage dependencies– Accesses node registry to download and install packages

• Install Karma– npm install –g karma– Needs internet connection to access the https://www.npmjs.org/ registry

• Install Karma Command Line Interface– npm install –g karma-cli– Needs internet connection to access the https://www.npmjs.org/ registry

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Setting-up the Environment• Generate the karma-configuration file

– karma init glarimy.config.js• Answer interactive questions• Opt for jasmine as the test framework• Choose your browser• Provide an expression/s for matching the test files (like *.js, *.test.js and etc., )• Provide an expression/s for exclusions from the above

• Develop Jasmine Test Cases– The location of the test cases must match the file entries in the karma

configuration file

• Run the test cases– karma start glarimy.config.js– The browser opens up automatically

• The status is available at http://localhost:9876• Results are displayed on the terminal

– Karma runs the tests whenever the file changes

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Testing using Jasmine• Prepare a test suite

– describe(“name”, function(){…});– Add optional setup and teardown routines

• beforeEach(function(){…});

– Add any number of test specifications to the suite• it(“name”, function(){…});• Set any number of expectations in the specifications

– expect(actualValue).toBe(expectedValue);

• Use appropriate matchers

– Employ spies for spying and mocking, if needed• var spy = createSpy(object-ref, “method-name”);• expect(spy).toHaveBeanCalled().and.returnValue(value);

• Run the test suite– You may use Karma for this purpose

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Karma Test Configuration• Can be placed anywhere, typically in the workspace• To be named as .js file

module.exports = function(config) { config.set({

basePath: ‘D:\Glarimy\Workspace\AngualrJS\',frameworks: ['jasmine'],files: ['*.js', 'tests/*.js’],exclude: [],

port: 9876,colors: true,logLevel: config.LOG_INFO,autoWatch: true,browsers: ['Firefox'],singleRun: false

});};

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Testing using Jasmine• Source Code: glarimy-calculator.js

function GlarimyCountingCalculator() {var count = 0;this.add = function(a, b){

count++;return a+b;

};this.subtract = function(a, b){

count++;return a-b;

};this.getCount = function(){

return count;}

}

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Testing using Jasmine• Jasmine Test Suite: glarimy-calculator-test.js

describe("GlarimyCountingCalculator", function() {beforeEach(function(){

this.calc = new GlarimyCountingCalculator(); });afterEach(function(){ });it("to add correctly", function() {

expect(this.calc.add(10,20)).toBe(30);});it("to subtract correctly", function() {

expect(this.calc.subtract(10,20)).toBe(-10);});it("to count correctly", function() {

expect(this.calc.getCount()).toBe(0);});

});

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Jasmine Matchers• For booleans

– toBeTruthy, toBeFalsy

• For numbers– Not, toBe, toEqual, – toBeLessThan, toBeGreaterThan, – toBeCloseTo

• For objects– toBeDefined, toBeUndefined, toBeNull

• For strings– toMatch

• For Arrays– toContain

• And – toThrow

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Jasmine Custom Matchers• Custom Matchers added in beforeEach

– Customer Matchers may override existing matchersdescribe("GlarimyCountingCalculator", function() {

beforeEach(function(){this.calc = new GlarimyCountingCalculator();this.addMatchers({

toBeEven: function(){var actual = this.actual;this.message = function(){

return actual + ' is not an even number';

}return (actual % 2 == 0)?true:false;

}});

});it("to add correctly", function() {

var sum = this.calc.add(10,20);expect(sum*2).toBeEven();

});});

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Jasmine Spies• Spies on calls to functions

– By adding a proxy to intercept the calls

function GlarimyDAO() {this.get = function(isbn){

return "Title: Java " + isbn;};

}

function GlarimyLibrary(dao){var _dao = dao;this.find = function(isbn){

if(isbn > 0)return _dao.get(isbn);

}}

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Jasmine Spies• Spies on calls to functions

describe("GlarimyLibrary", function(){beforeEach(function(){

this.dao = new GlarimyDAO();this.library = new GlarimyLibrary(this.dao);spyOn(this.dao, 'get');

});it('to find correctly', function(){

this.library.find(1234);expect(this.dao.get).toHaveBeenCalled();

});it('to find correctly', function(){

this.library.find(-1234);expect(this.dao.get).not.toHaveBeenCalled();

});})

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Testing Angular• Use Angular Mock Objects

– npm install angular-mocks

• Test Development– Create application modules in the suites– Inject the $rootscope, $controller and required servicesdescribe('suite name', function(){ var scope, controller; beforeEach(module('module-name')); beforeEach(inject( function($rootScope, $controller){

scope = $rootScope.$new(); controller = $controller; controller('controller-name', {'$scope': scope});

}));it('spec-name', function(){

expect(scope.scope-variable).toBe(value);});

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Testing Angulardescribe('GlarimyDirectoryController-6', function(){ var scope, controller, GlarimyDirectoryService, httpBackend; beforeEach(module('GlarimyDirectory-6')); beforeEach(inject( function($rootScope, $controller, _GlarimyDirectoryService_,

$httpBackend){ httpBackend = $httpBackend; httpBackend.when('GET', 'contacts.json').respond({

"list":[{"id": 1,"name": "Krishna","phoneNumber": 9731423166

}]});

GlarimyDirectoryService = _GlarimyDirectoryService_; scope = $rootScope.$new(); controller = $controller; controller('GlarimyDirectoryController', {'$scope': scope, 'GlarimyDirectoryService': GlarimyDirectoryService});

}));// to be continued in the next slide

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Testing Angular//Continued from previous slideit('should have variable contacts"', function(){ httpBackend.flush(); expect(scope.contacts).not.toBeNull(); expect(scope.contacts[0]).toEqual({

"id": 1,"name": "Krishna","phoneNumber": 9731423166

});

expect(GlarimyDirectoryService.list().length).toBe(1);

});});

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Thank YouGlarimy Technology Services

Consulting, Corporate Training & Weekend Executive Workshops

http://www.glarimy.com | [email protected]

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

•Java: JSE, JEE, JPA, Spring, Hibernate, SOAP/XML, REST, JSF•Web: HTML5, CSS3, Object Oriented JavaScript, AJAX•Web 2.0: JQuery, ExtJS, Dojo, AngularJS•Design and Architecture: OOAD, UML, Design Patterns, Integration Patterns

Technologies

•Karnataka: Bangalore and Mysore•Tamilnadu: Chennai, Coimbatore•Andhra Pradesh: Visakhapatnam, Vijayawada, Tirupati•Telangana: Hyderabad•Kerala: Kochi, Trivendrum•Maharashtra: Mumbai, Pune

Reach

•Architectural Consulting: Development, Review, Enhancement•Construction: Coding, Reviews, Refactoring•Corporate Training•Weekend Workshops: Fridays and Saturdays

Services

Glarimy Technology Services

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com