SlideShare a Scribd company logo
An Introduction to AngularJs Unit
Testing
Topics
•
What’re Karma & Jasmine?
•
Suites & Specs
•
beforeEach & afterEach (Setup & TearDown)
•
Expectations (Assertions)
•
Spies (Mocks & Stubs)
•
Exercise I (Hello World)
•
Exercise II (BMI Calculator Controller)
•
Q & A
Karma & Jasmine
Karma is a JavaScript command line tool that can
be used to spawn a web server which loads your
application's source code and executes your tests
(http://karma-runner.github.io/)
Jasmine provides functions to help with structuring
your tests and also making assertions. As your tests
grow, keeping them well structured and documented
is vital, and Jasmine helps achieve this.
(http://jasmine.github.io/)
Suites & Specs
Suites: describe()
A test suite begins with a call to the global Jasmine function
describe with two parameters: a string and a function. The
string is a name or title for a spec suite – usually what is being
tested. The function is a block of code that implements the
suite.
Specs: it()
specs are defined by calling the global Jasmine function it,
which, like describe takes a string and a function. The string
is the title of the spec and the function is the spec, or test. A
spec contains one or more expectations that test the state of
the code. An expectation in Jasmine is an assertion that is
either true or false. A spec with all true expectations is a
passing spec. A spec with one or more false expectations is a
failing spec.
Suites & Specs
(Con.)
PHP
class CalculatorTest extends
PHPUnit_Framework_TestCase{
public function
testCaculate2DigitsThenReturnTrue()
{
…
}
public function
testCaculate2CharsThenReturnFalse(){
…
}
}
Jasmine
describe("test calculator", function () {
it(“test calculate 2 digits then return true”,
function(){
…
});
it(“test calculate 2 chars then return true”,
function(){
…
});
});
beforeEach & afterEach (Setup &
Teardown)
PHP
class UnitTest extends PHPUnit_Framework_TestCase{
public function setUp(){
…
}
public function tearDown(){
…
}
}
Jasmine
describe("test hello world controller", function () {
beforeEach(function(){
….
});
afterEach(function () {
….
});
});
Expectations
(Assertions)
PHP VS Jasmine
assertContains(“world”, “hello world”) vs expect(“hello world”).toContain("world")
assertEquals(“success”, “success”) vs expect(“success”).toEqual(“success”)
assertNotEquals(“fail”, “success”) vs expect(“fail”).not.toEqual(“success”)
assertTrue(true) vs expect(true).toBeTruthy()
assertFalse(false) vs expect(false).toBeFalsy()
assertGreaterThan(1, 2) vs expect(2).toBeGreaterThan(1)
assertLessThan(2, 1) vs expect(1).toBeLessThan(2)
assertRegExp('/foo/', ‘yo ya foo’) vs expect(“yo ya foo”).toMatch(/foo/)
assertNull(null) vs expect(null).toBeNull()
assertNotNull(“not null”) vs expect(“not null”).not.toBeNull()
Spies (Mocks & Stubs)
PHP
public function setUp(){
$this->mock = $this
->getMockBuilder('HelloWorldClass')
->getMock();
$this->mock
->expects($this->once())
->method('printHelloWorld')
->with($this->anything())
->will($this->returnValue(“Hello World”));
}
Jasmine
beforeEach(function(){
spyOn(HelloWorldClass, “printHelloWorld”)
.and.returnValue(“Hello World);
});
it(“test printHelloWorld function”, function(){
expect(HelloWorldClass.printHelloWorld.calls.count
())
.toEqual(1);
expect(HelloWorldClass.printHelloWorld)
.
toHaveBeenCalledWith(jasmine.anything());
});
Exercise I
1.Clone https://github.com/inthra-onsap/angular-
unittesting-lab
2.Create spec file inside test/spec. (file_name:
hello_world.spec.js)
3.Put the code here inside:
"use strict"
var HelloWorldClass = {
printHelloWorld: function(){
return "Hello world";
}
};
describe("Hello world suite", function(){
it("test printHelloWorld method", function(){
expect(HelloWorldClass.printHelloWorld()).toEqual("Hello world”);
});
});
4. Open terminal and then execute “grunt test”
Exercise II
Body Mass Index(BMI) Calculation
BMI = weight/(height/100*height/100)
Specs:
1.To proof weight and height are GREATER THAN 0 (zero)
otherwise display “ERROR”.
2.To proof in case of BMI value is LOWER THAN or EQUAL
18.5 then display “You are too THIN”.
3.To proof in case of BMI value is GREATER THAN 18.5 and
LOWER THAN or EQUAL 25 then display “You are so
(HANDSOME or BEAUTIFUL)”.
4.To proof in case of BMI value is GREATER THAN 25 then
display “You are too FAT”.
One more thing…
CODE COVERAGE
Q & A

More Related Content

What's hot

Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
jeresig
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
Jim Lynch
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
Kissy Team
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and Karma
Christopher Bartling
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
Jim Lynch
 
xUnit Style Database Testing
xUnit Style Database TestingxUnit Style Database Testing
xUnit Style Database Testing
Chris Oldwood
 
Krazykoder struts2 interceptors
Krazykoder struts2 interceptorsKrazykoder struts2 interceptors
Krazykoder struts2 interceptorsKrazy Koder
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
Anup Singh
 
Redux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncRedux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with Async
Artur Szott
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
Andrea Paciolla
 
MeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenment
Artur Szott
 
Angular JS Unit Testing - Overview
Angular JS Unit Testing - OverviewAngular JS Unit Testing - Overview
Angular JS Unit Testing - Overview
Thirumal Sakthivel
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
Knoldus Inc.
 
Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with EasymockÜrgo Ringo
 
Unit testing
Unit testingUnit testing
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
Rafael Winterhalter
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test framework
Abner Chih Yi Huang
 
Java custom annotations example
Java custom annotations exampleJava custom annotations example
Java custom annotations example
Milton José Ferreira
 
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile appsTech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Fandy Gotama
 
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
Tech in Asia ID
 

What's hot (20)

Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and Karma
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 
xUnit Style Database Testing
xUnit Style Database TestingxUnit Style Database Testing
xUnit Style Database Testing
 
Krazykoder struts2 interceptors
Krazykoder struts2 interceptorsKrazykoder struts2 interceptors
Krazykoder struts2 interceptors
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
Redux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncRedux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with Async
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
MeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenment
 
Angular JS Unit Testing - Overview
Angular JS Unit Testing - OverviewAngular JS Unit Testing - Overview
Angular JS Unit Testing - Overview
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
 
Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with Easymock
 
Unit testing
Unit testingUnit testing
Unit testing
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test framework
 
Java custom annotations example
Java custom annotations exampleJava custom annotations example
Java custom annotations example
 
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile appsTech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
 
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
 

Viewers also liked

Angular js, Yeomon & Grunt
Angular js, Yeomon & GruntAngular js, Yeomon & Grunt
Angular js, Yeomon & Grunt
Richard Powell
 
Grunt js and WordPress
Grunt js and WordPressGrunt js and WordPress
Grunt js and WordPress
WP Australia
 
Mastering Grunt
Mastering GruntMastering Grunt
Mastering Grunt
Spencer Handley
 
GruntJS + Wordpress
GruntJS + WordpressGruntJS + Wordpress
GruntJS + Wordpress
Leonardo Balter
 
Wrangling the WordPress Template Hierarchy Like a Boss
Wrangling the WordPress Template Hierarchy Like a BossWrangling the WordPress Template Hierarchy Like a Boss
Wrangling the WordPress Template Hierarchy Like a Boss
IntrepidRealist
 
WordPress Theme Development Workflow with Node.js, Ruby, Sass, Bower and Grunt
WordPress Theme Development Workflow with Node.js, Ruby, Sass, Bower and GruntWordPress Theme Development Workflow with Node.js, Ruby, Sass, Bower and Grunt
WordPress Theme Development Workflow with Node.js, Ruby, Sass, Bower and Grunt
Brajeshwar Oinam
 
Metadata and me
Metadata and meMetadata and me
Metadata and me
Nick Sheppard
 
A Quick and Dirty D3.js Tutorial
A Quick and Dirty D3.js TutorialA Quick and Dirty D3.js Tutorial
A Quick and Dirty D3.js Tutorial
Young-Ho Kim
 
Come migliorare le performance di WordPress con il Visual Composer
Come migliorare le performance di WordPress con il Visual ComposerCome migliorare le performance di WordPress con il Visual Composer
Come migliorare le performance di WordPress con il Visual Composer
liciapelliconi.it
 
Javascript testing: tools of the trade
Javascript testing: tools of the tradeJavascript testing: tools of the trade
Javascript testing: tools of the trade
Juanma Orta
 
Using Composer to create manageable WordPress websites
Using Composer to create manageable WordPress websitesUsing Composer to create manageable WordPress websites
Using Composer to create manageable WordPress websites
Anna Ladoshkina
 
WordPress Database: What's behind those 12 tables
WordPress Database: What's behind those 12 tablesWordPress Database: What's behind those 12 tables
WordPress Database: What's behind those 12 tables
Mauricio Gelves
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
WordPress Template Hierarchy
WordPress Template HierarchyWordPress Template Hierarchy
WordPress Template Hierarchy
Sarah Whinnem
 
Getting Started With Grunt for WordPress Development
Getting Started With Grunt for WordPress DevelopmentGetting Started With Grunt for WordPress Development
Getting Started With Grunt for WordPress Development
David Bisset
 

Viewers also liked (15)

Angular js, Yeomon & Grunt
Angular js, Yeomon & GruntAngular js, Yeomon & Grunt
Angular js, Yeomon & Grunt
 
Grunt js and WordPress
Grunt js and WordPressGrunt js and WordPress
Grunt js and WordPress
 
Mastering Grunt
Mastering GruntMastering Grunt
Mastering Grunt
 
GruntJS + Wordpress
GruntJS + WordpressGruntJS + Wordpress
GruntJS + Wordpress
 
Wrangling the WordPress Template Hierarchy Like a Boss
Wrangling the WordPress Template Hierarchy Like a BossWrangling the WordPress Template Hierarchy Like a Boss
Wrangling the WordPress Template Hierarchy Like a Boss
 
WordPress Theme Development Workflow with Node.js, Ruby, Sass, Bower and Grunt
WordPress Theme Development Workflow with Node.js, Ruby, Sass, Bower and GruntWordPress Theme Development Workflow with Node.js, Ruby, Sass, Bower and Grunt
WordPress Theme Development Workflow with Node.js, Ruby, Sass, Bower and Grunt
 
Metadata and me
Metadata and meMetadata and me
Metadata and me
 
A Quick and Dirty D3.js Tutorial
A Quick and Dirty D3.js TutorialA Quick and Dirty D3.js Tutorial
A Quick and Dirty D3.js Tutorial
 
Come migliorare le performance di WordPress con il Visual Composer
Come migliorare le performance di WordPress con il Visual ComposerCome migliorare le performance di WordPress con il Visual Composer
Come migliorare le performance di WordPress con il Visual Composer
 
Javascript testing: tools of the trade
Javascript testing: tools of the tradeJavascript testing: tools of the trade
Javascript testing: tools of the trade
 
Using Composer to create manageable WordPress websites
Using Composer to create manageable WordPress websitesUsing Composer to create manageable WordPress websites
Using Composer to create manageable WordPress websites
 
WordPress Database: What's behind those 12 tables
WordPress Database: What's behind those 12 tablesWordPress Database: What's behind those 12 tables
WordPress Database: What's behind those 12 tables
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
 
WordPress Template Hierarchy
WordPress Template HierarchyWordPress Template Hierarchy
WordPress Template Hierarchy
 
Getting Started With Grunt for WordPress Development
Getting Started With Grunt for WordPress DevelopmentGetting Started With Grunt for WordPress Development
Getting Started With Grunt for WordPress Development
 

Similar to An Introduction to AngularJs Unittesting

Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and Karma
Andrey Kolodnitsky
 
Slaven tomac unit testing in angular js
Slaven tomac   unit testing in angular jsSlaven tomac   unit testing in angular js
Slaven tomac unit testing in angular jsSlaven Tomac
 
JavaCro'14 - Unit testing in AngularJS – Slaven Tomac
JavaCro'14 - Unit testing in AngularJS – Slaven TomacJavaCro'14 - Unit testing in AngularJS – Slaven Tomac
JavaCro'14 - Unit testing in AngularJS – Slaven Tomac
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Unit testing using jasmine in Javascript
Unit testing using jasmine in JavascriptUnit testing using jasmine in Javascript
Unit testing using jasmine in Javascript
Deepak More
 
Unit Testing Front End JavaScript
Unit Testing Front End JavaScriptUnit Testing Front End JavaScript
Unit Testing Front End JavaScript
FITC
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingAnna Khabibullina
 
NetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience ReportNetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience ReportAnton Arhipov
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
jeresig
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with example
shadabgilani
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
GlobalLogic Ukraine
 
E2E testing con nightwatch.js - Drupalcamp Spain 2018
E2E testing con nightwatch.js  - Drupalcamp Spain 2018E2E testing con nightwatch.js  - Drupalcamp Spain 2018
E2E testing con nightwatch.js - Drupalcamp Spain 2018
Salvador Molina (Slv_)
 
Good Practices On Test Automation
Good Practices On Test AutomationGood Practices On Test Automation
Good Practices On Test Automation
Gustavo Labbate Godoy
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
FITC
 
Jtr Fosdem 09
Jtr Fosdem 09Jtr Fosdem 09
Jtr Fosdem 09
fruxo
 
Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)
Anis Bouhachem Djer
 
Quick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineQuick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using Jasmine
Gil Fink
 
S313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discoveringS313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discovering
romanovfedor
 

Similar to An Introduction to AngularJs Unittesting (20)

Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and Karma
 
jasmine
jasminejasmine
jasmine
 
Slaven tomac unit testing in angular js
Slaven tomac   unit testing in angular jsSlaven tomac   unit testing in angular js
Slaven tomac unit testing in angular js
 
JavaCro'14 - Unit testing in AngularJS – Slaven Tomac
JavaCro'14 - Unit testing in AngularJS – Slaven TomacJavaCro'14 - Unit testing in AngularJS – Slaven Tomac
JavaCro'14 - Unit testing in AngularJS – Slaven Tomac
 
Unit testing using jasmine in Javascript
Unit testing using jasmine in JavascriptUnit testing using jasmine in Javascript
Unit testing using jasmine in Javascript
 
Unit Testing Front End JavaScript
Unit Testing Front End JavaScriptUnit Testing Front End JavaScript
Unit Testing Front End JavaScript
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testing
 
NetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience ReportNetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience Report
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with example
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
E2E testing con nightwatch.js - Drupalcamp Spain 2018
E2E testing con nightwatch.js  - Drupalcamp Spain 2018E2E testing con nightwatch.js  - Drupalcamp Spain 2018
E2E testing con nightwatch.js - Drupalcamp Spain 2018
 
Good Practices On Test Automation
Good Practices On Test AutomationGood Practices On Test Automation
Good Practices On Test Automation
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
Jtr Fosdem 09
Jtr Fosdem 09Jtr Fosdem 09
Jtr Fosdem 09
 
Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)
 
Jdbc
JdbcJdbc
Jdbc
 
Quick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineQuick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using Jasmine
 
S313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discoveringS313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discovering
 

An Introduction to AngularJs Unittesting

  • 1. An Introduction to AngularJs Unit Testing
  • 2. Topics • What’re Karma & Jasmine? • Suites & Specs • beforeEach & afterEach (Setup & TearDown) • Expectations (Assertions) • Spies (Mocks & Stubs) • Exercise I (Hello World) • Exercise II (BMI Calculator Controller) • Q & A
  • 3. Karma & Jasmine Karma is a JavaScript command line tool that can be used to spawn a web server which loads your application's source code and executes your tests (http://karma-runner.github.io/) Jasmine provides functions to help with structuring your tests and also making assertions. As your tests grow, keeping them well structured and documented is vital, and Jasmine helps achieve this. (http://jasmine.github.io/)
  • 4. Suites & Specs Suites: describe() A test suite begins with a call to the global Jasmine function describe with two parameters: a string and a function. The string is a name or title for a spec suite – usually what is being tested. The function is a block of code that implements the suite. Specs: it() specs are defined by calling the global Jasmine function it, which, like describe takes a string and a function. The string is the title of the spec and the function is the spec, or test. A spec contains one or more expectations that test the state of the code. An expectation in Jasmine is an assertion that is either true or false. A spec with all true expectations is a passing spec. A spec with one or more false expectations is a failing spec.
  • 5. Suites & Specs (Con.) PHP class CalculatorTest extends PHPUnit_Framework_TestCase{ public function testCaculate2DigitsThenReturnTrue() { … } public function testCaculate2CharsThenReturnFalse(){ … } } Jasmine describe("test calculator", function () { it(“test calculate 2 digits then return true”, function(){ … }); it(“test calculate 2 chars then return true”, function(){ … }); });
  • 6. beforeEach & afterEach (Setup & Teardown) PHP class UnitTest extends PHPUnit_Framework_TestCase{ public function setUp(){ … } public function tearDown(){ … } } Jasmine describe("test hello world controller", function () { beforeEach(function(){ …. }); afterEach(function () { …. }); });
  • 7. Expectations (Assertions) PHP VS Jasmine assertContains(“world”, “hello world”) vs expect(“hello world”).toContain("world") assertEquals(“success”, “success”) vs expect(“success”).toEqual(“success”) assertNotEquals(“fail”, “success”) vs expect(“fail”).not.toEqual(“success”) assertTrue(true) vs expect(true).toBeTruthy() assertFalse(false) vs expect(false).toBeFalsy() assertGreaterThan(1, 2) vs expect(2).toBeGreaterThan(1) assertLessThan(2, 1) vs expect(1).toBeLessThan(2) assertRegExp('/foo/', ‘yo ya foo’) vs expect(“yo ya foo”).toMatch(/foo/) assertNull(null) vs expect(null).toBeNull() assertNotNull(“not null”) vs expect(“not null”).not.toBeNull()
  • 8. Spies (Mocks & Stubs) PHP public function setUp(){ $this->mock = $this ->getMockBuilder('HelloWorldClass') ->getMock(); $this->mock ->expects($this->once()) ->method('printHelloWorld') ->with($this->anything()) ->will($this->returnValue(“Hello World”)); } Jasmine beforeEach(function(){ spyOn(HelloWorldClass, “printHelloWorld”) .and.returnValue(“Hello World); }); it(“test printHelloWorld function”, function(){ expect(HelloWorldClass.printHelloWorld.calls.count ()) .toEqual(1); expect(HelloWorldClass.printHelloWorld) . toHaveBeenCalledWith(jasmine.anything()); });
  • 9. Exercise I 1.Clone https://github.com/inthra-onsap/angular- unittesting-lab 2.Create spec file inside test/spec. (file_name: hello_world.spec.js) 3.Put the code here inside: "use strict" var HelloWorldClass = { printHelloWorld: function(){ return "Hello world"; } }; describe("Hello world suite", function(){ it("test printHelloWorld method", function(){ expect(HelloWorldClass.printHelloWorld()).toEqual("Hello world”); }); }); 4. Open terminal and then execute “grunt test”
  • 10. Exercise II Body Mass Index(BMI) Calculation BMI = weight/(height/100*height/100) Specs: 1.To proof weight and height are GREATER THAN 0 (zero) otherwise display “ERROR”. 2.To proof in case of BMI value is LOWER THAN or EQUAL 18.5 then display “You are too THIN”. 3.To proof in case of BMI value is GREATER THAN 18.5 and LOWER THAN or EQUAL 25 then display “You are so (HANDSOME or BEAUTIFUL)”. 4.To proof in case of BMI value is GREATER THAN 25 then display “You are too FAT”.
  • 12. Q & A