SlideShare a Scribd company logo
1 of 34
Download to read offline
Unit Testing in Practice
nirkaufman@gmail.com
Download the reference project at:
https://github.com/nirkaufman/angularjs-unit-testing-demo
contact me at: nirkaufman@gmail.com
or
http://www.linkedin.com/in/nirkaufman
nirkaufman@gmail.com
Getting Started with Unit Testing
Intruduction
nirkaufman@gmail.com
About Unit Testing
The primary goal of unit testing is to take the smallest piece of testable
software in the application, isolate it from the remainder of the code, and
determine whether it behaves exactly as you expect.
nirkaufman@gmail.com
Testing AngularJS App`s
AngularJS build around the concept of dependency injection & loose coupling
to the DOM which make it a very tesable.
nirkaufman@gmail.com
Test Driven Developemnt
a software development process that relies on the repetition of a very short
development cycle: first the developer writes an (initially failing) automated
test case that defines a desired improvement or new function, then produces
the minimum amount of code to pass that test, and finally refactors the new
code to acceptable standards.
nirkaufman@gmail.com
RED
(fail)
Green
(pass)
REFACTO
R
1. write a test that fails
2. write only enougth
code to make it pass
3. improve code quality
Test Driven Developemnt
nirkaufman@gmail.com
The main goal for Karma is to bring a productive testing environment to
developers. The environment being one where they don't have to set up
loads of configurations, but rather a place where developers can just write
the code and get instant feedback from their tests. Because getting quick
feedback is what makes you productive and creative.
http://karma-runner.github.io/
nirkaufman@gmail.com
Jasmine is a behavior-driven development framework for testing
JavaScript code. It does not depend on any other JavaScript
frameworks. It does not require a DOM. And it has a clean, obvious
syntax so that you can easily write tests.
http://jasmine.github.io/
nirkaufman@gmail.com
Setting up our TDD Enveirment
Project Setup
nirkaufman@gmail.com
Let`s start from scratch.
First, we need to create a basic project structure with a
folder that contain our sources, and a folder that
contains our specs. then we can init a package.json
$ npm init
nirkaufman@gmail.com
$ npm install karma
let`s install Karma (and all the plugins your project
needs) locally in the project's directory.
(don`t forget to use the --save-dev flags)
nirkaufman@gmail.com
$ npm install karma-jasmine
$ npm install karma-chrome-launcher
since we going to use jasmine, let`s install tha karma
adaptor plugin for jasmine.
we will also install the chrome launcher plugin to enable
karma to launch chrome browser fo us
nirkaufman@gmail.com
$ npm install -g karma-cli
Finally, we will install the karma command line interface
(cli) globally, which enable us to easily configure karma
in our project
nirkaufman@gmail.com
$ karma init
with the karma cli installed, we can create our
configuration file fast and easy.
nirkaufman@gmail.com
$ karma start
$ karma run
Let`s take karma for a test drive:
in webstorm, right click on the configuration file and
choose run.
if you don`t use webstorm, start the karma server with
start, and run you tests with run
nirkaufman@gmail.com
quick intruduction to the Jasmine framwork
Jasmine 101
nirkaufman@gmail.com
describe("suite name", function() {
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
});
in jasmine, we begin by creating a test suite with the
global describe function that wrap our specs.
specs are defined by the global function it.
inside the spec we can describe our expextations by
using tha expect function chained to a matcher function
nirkaufman@gmail.com
describe("suite name", function() {
beforeEach(function () {//excute before each spec})
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
afterEach(function () {//excute after each spec})
});
we can run code before and after each spec in a suite
block using the beforeEach and afterEach functions
nirkaufman@gmail.com
// spy on the method setBar of foo object
spyOn(foo, 'setBar');
it("contains spec with an expectation", function() {
expect(foo.setBar).toHaveBeenCalled();
expect(foo.setBar).toHaveBeenCalledWith(32);
});
});
jasmine use spies to track calls to a function with all it`s
arguments.
There are special matchers for interacting with spies.
The toHaveBeenCalled and The
toHaveBeenCalledWith
nirkaufman@gmail.com
Test Driven Development in practice
Testing AngularJS
nirkaufman@gmail.com
$ bower install angular
$ bower install angular-mocks
We are going to develop a small Task Manger app.
in the process we will learn how to unit test the building
blocks of every AngularJS application:
controllers, services, directives, events & http requests.
First, let`s get some resources using bower
nirkaufman@gmail.com
Controllers
nirkaufman@gmail.com
// get the module that contain the controller
beforeEach(module('todolist'));
// inject the $controller and the rootScope
beforeEach(inject(function ($rootScope, $controller) {
// create a fresh new scope for the controller
scope = $rootScope.$new();
// create a controller with this scope
ctrl = $controller('TodoListController',{$scope: scope});
}));
In order to test controllers we need to holds an instance
of the controller, initialize a scope for it and testing our
expectations against that scope.
nirkaufman@gmail.com
services
Services
nirkaufman@gmail.com
// get the module that contain the service
beforeEach(module('todolist'));
// inject the $injector
beforeEach(inject(function ($injector) {
// use the $injector to get a hold on the service
service = $injector.get(‘ServiceName’);
}));
In order to test services we need to use the $injector to
get an instance of the service
nirkaufman@gmail.com
Directive
nirkaufman@gmail.com
// get the module that contain the service
beforeEach(module('todolist'));
// inject the $compile service and the $rootScope
beforeEach(inject(function ($compile, $rootScope) {
// use the $rootScope to create a scope for the directive
scope = $rootScope;
// create an angular element from a HTML string
element = angular.element(‘<div my-directive ></div>’)
// compile the element with the scope
$compile(element)(scope)
scope.$apply()
}));
In order to test a directive, we need to create an
element that will host the directive and compile it with a
scope. in our spec, we need trigger the digest.
nirkaufman@gmail.com
http requests
nirkaufman@gmail.com
// inject the $httpBackend service and the $rootScope
beforeEach(inject(function ($httpBackend) {
// use the $rootScope to create a scope for the directive
httpBackend = $httpBackend;
it("somting that make a request", function() {
// expect a request
httpBackend.expectGET(‘api’).respond(200);
// code that make a request
httpBackend.flush(); // do`nt forget to flush..
});
}));
the $httpBackend is a fake HTTP Back-end
implementaion. in the most basic use we can verify that
a request is made & stub responses
nirkaufman@gmail.com
Productive Tips
Making testing even more easier
nirkaufman@gmail.com
When the number of test suites and specs grows larger,
the overall test speed is affected.
jasmine include some usfull syntax to control it.
// run this usite
ddescribe()
// run this spec
iit()
// run this spec
xit()
webstorm users can install the ddescriber for jasmine
nirkaufman@gmail.com
in webstorm the run panel enable us some more
featuers like:
Set Auto Test Delay Time
Export Test Results
Filter and sort
Run / Debug Configuration
live templates
nirkaufman@gmail.com
Thank You!
Download the reference project at:
https://github.com/nirkaufman/angularjs-unit-testing-demo
contact me at: nirkaufman@gmail.com
or
http://www.linkedin.com/in/nirkaufman

More Related Content

What's hot

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
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSKnoldus Inc.
 
Unit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introMaurice De Beijer [MVP]
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaChristopher Bartling
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingLars Thorup
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSJim Lynch
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsFITC
 
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 jasmineGil Fink
 
Angular JS Unit Testing - Overview
Angular JS Unit Testing - OverviewAngular JS Unit Testing - Overview
Angular JS Unit Testing - OverviewThirumal Sakthivel
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQueryKnoldus Inc.
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with JestMichał Pierzchała
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with JasmineTim Tyrrell
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript TestingScott Becker
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Roy Yu
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Morris Singer
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsYnon Perek
 

What's hot (20)

Angular testing
Angular testingAngular testing
Angular testing
 
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
 
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 JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma intro
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and Karma
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
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
 
Angular JS Unit Testing - Overview
Angular JS Unit Testing - OverviewAngular JS Unit Testing - Overview
Angular JS Unit Testing - Overview
 
Jasmine BDD for Javascript
Jasmine BDD for JavascriptJasmine BDD for Javascript
Jasmine BDD for Javascript
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQuery
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript Testing
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
 

Similar to Angularjs - Unit testing introduction

Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciollaAndrea Paciolla
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with exampleshadabgilani
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
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 jasmineGil Fink
 
Exploring Angular 2 - Episode 1
Exploring Angular 2 - Episode 1Exploring Angular 2 - Episode 1
Exploring Angular 2 - Episode 1Ahmed Moawad
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Frost
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidenceJohn Congdon
 
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...Katy Slemon
 
One commit, one release. Continuously delivering a Symfony project.
One commit, one release. Continuously delivering a Symfony project.One commit, one release. Continuously delivering a Symfony project.
One commit, one release. Continuously delivering a Symfony project.Javier López
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular IntermediateLinkMe Srl
 
RichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile DevicesRichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile DevicesPavol Pitoňák
 
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-AppsSelenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-Appschrisb206 chrisb206
 
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...Wim Selles
 
Continous Delivering a PHP application
Continous Delivering a PHP applicationContinous Delivering a PHP application
Continous Delivering a PHP applicationJavier López
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in detailsMax Klymyshyn
 
JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...
JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...
JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...Yusuke Yamamoto
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & PromisesKnoldus Inc.
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Ontico
 

Similar to Angularjs - Unit testing introduction (20)

Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with example
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
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
 
Exploring Angular 2 - Episode 1
Exploring Angular 2 - Episode 1Exploring Angular 2 - Episode 1
Exploring Angular 2 - Episode 1
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
 
An Overview of Angular 4
An Overview of Angular 4 An Overview of Angular 4
An Overview of Angular 4
 
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
 
One commit, one release. Continuously delivering a Symfony project.
One commit, one release. Continuously delivering a Symfony project.One commit, one release. Continuously delivering a Symfony project.
One commit, one release. Continuously delivering a Symfony project.
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
 
RichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile DevicesRichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile Devices
 
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-AppsSelenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
 
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
 
Continous Delivering a PHP application
Continous Delivering a PHP applicationContinous Delivering a PHP application
Continous Delivering a PHP application
 
Automation Zaman Now
Automation Zaman NowAutomation Zaman Now
Automation Zaman Now
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 
JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...
JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...
JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
 

More from Nir Kaufman

Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency InjectionNir Kaufman
 
Angular Prestige: Less-known API and techniques
Angular Prestige: Less-known API and techniquesAngular Prestige: Less-known API and techniques
Angular Prestige: Less-known API and techniquesNir Kaufman
 
Angular CLI custom builders
Angular CLI custom buildersAngular CLI custom builders
Angular CLI custom buildersNir Kaufman
 
Electronic music 101 for developers
Electronic music 101 for developersElectronic music 101 for developers
Electronic music 101 for developersNir Kaufman
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass SlidesNir Kaufman
 
Redux pattens - JSHeroes 2018
Redux pattens - JSHeroes 2018Redux pattens - JSHeroes 2018
Redux pattens - JSHeroes 2018Nir Kaufman
 
Angular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir KaufmanAngular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir KaufmanNir Kaufman
 
Boosting Angular runtime performance
Boosting Angular runtime performanceBoosting Angular runtime performance
Boosting Angular runtime performanceNir Kaufman
 
Decorators in js
Decorators in jsDecorators in js
Decorators in jsNir Kaufman
 
Styling recipes for Angular components
Styling recipes for Angular componentsStyling recipes for Angular components
Styling recipes for Angular componentsNir Kaufman
 
Introduction To Angular's reactive forms
Introduction To Angular's reactive formsIntroduction To Angular's reactive forms
Introduction To Angular's reactive formsNir Kaufman
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Nir Kaufman
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes WorkshopNir Kaufman
 
Data Structures in javaScript 2015
Data Structures in javaScript 2015Data Structures in javaScript 2015
Data Structures in javaScript 2015Nir Kaufman
 
redux and angular - up and running
redux and angular - up and runningredux and angular - up and running
redux and angular - up and runningNir Kaufman
 
How Angular2 Can Improve Your AngularJS Apps Today!
How Angular2 Can Improve Your AngularJS Apps Today!How Angular2 Can Improve Your AngularJS Apps Today!
How Angular2 Can Improve Your AngularJS Apps Today!Nir Kaufman
 
Angular2 workshop
Angular2 workshopAngular2 workshop
Angular2 workshopNir Kaufman
 

More from Nir Kaufman (20)

Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 
Angular Prestige: Less-known API and techniques
Angular Prestige: Less-known API and techniquesAngular Prestige: Less-known API and techniques
Angular Prestige: Less-known API and techniques
 
Angular CLI custom builders
Angular CLI custom buildersAngular CLI custom builders
Angular CLI custom builders
 
Electronic music 101 for developers
Electronic music 101 for developersElectronic music 101 for developers
Electronic music 101 for developers
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
Redux pattens - JSHeroes 2018
Redux pattens - JSHeroes 2018Redux pattens - JSHeroes 2018
Redux pattens - JSHeroes 2018
 
Angular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir KaufmanAngular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir Kaufman
 
Boosting Angular runtime performance
Boosting Angular runtime performanceBoosting Angular runtime performance
Boosting Angular runtime performance
 
Decorators in js
Decorators in jsDecorators in js
Decorators in js
 
Styling recipes for Angular components
Styling recipes for Angular componentsStyling recipes for Angular components
Styling recipes for Angular components
 
Introduction To Angular's reactive forms
Introduction To Angular's reactive formsIntroduction To Angular's reactive forms
Introduction To Angular's reactive forms
 
Webstorm
WebstormWebstorm
Webstorm
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes Workshop
 
Data Structures in javaScript 2015
Data Structures in javaScript 2015Data Structures in javaScript 2015
Data Structures in javaScript 2015
 
redux and angular - up and running
redux and angular - up and runningredux and angular - up and running
redux and angular - up and running
 
Angular redux
Angular reduxAngular redux
Angular redux
 
How Angular2 Can Improve Your AngularJS Apps Today!
How Angular2 Can Improve Your AngularJS Apps Today!How Angular2 Can Improve Your AngularJS Apps Today!
How Angular2 Can Improve Your AngularJS Apps Today!
 
Angular2 workshop
Angular2 workshopAngular2 workshop
Angular2 workshop
 
Solid angular
Solid angularSolid angular
Solid angular
 

Recently uploaded

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Recently uploaded (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

Angularjs - Unit testing introduction

  • 1. Unit Testing in Practice
  • 2. nirkaufman@gmail.com Download the reference project at: https://github.com/nirkaufman/angularjs-unit-testing-demo contact me at: nirkaufman@gmail.com or http://www.linkedin.com/in/nirkaufman
  • 3. nirkaufman@gmail.com Getting Started with Unit Testing Intruduction
  • 4. nirkaufman@gmail.com About Unit Testing The primary goal of unit testing is to take the smallest piece of testable software in the application, isolate it from the remainder of the code, and determine whether it behaves exactly as you expect.
  • 5. nirkaufman@gmail.com Testing AngularJS App`s AngularJS build around the concept of dependency injection & loose coupling to the DOM which make it a very tesable.
  • 6. nirkaufman@gmail.com Test Driven Developemnt a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards.
  • 7. nirkaufman@gmail.com RED (fail) Green (pass) REFACTO R 1. write a test that fails 2. write only enougth code to make it pass 3. improve code quality Test Driven Developemnt
  • 8. nirkaufman@gmail.com The main goal for Karma is to bring a productive testing environment to developers. The environment being one where they don't have to set up loads of configurations, but rather a place where developers can just write the code and get instant feedback from their tests. Because getting quick feedback is what makes you productive and creative. http://karma-runner.github.io/
  • 9. nirkaufman@gmail.com Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests. http://jasmine.github.io/
  • 10. nirkaufman@gmail.com Setting up our TDD Enveirment Project Setup
  • 11. nirkaufman@gmail.com Let`s start from scratch. First, we need to create a basic project structure with a folder that contain our sources, and a folder that contains our specs. then we can init a package.json $ npm init
  • 12. nirkaufman@gmail.com $ npm install karma let`s install Karma (and all the plugins your project needs) locally in the project's directory. (don`t forget to use the --save-dev flags)
  • 13. nirkaufman@gmail.com $ npm install karma-jasmine $ npm install karma-chrome-launcher since we going to use jasmine, let`s install tha karma adaptor plugin for jasmine. we will also install the chrome launcher plugin to enable karma to launch chrome browser fo us
  • 14. nirkaufman@gmail.com $ npm install -g karma-cli Finally, we will install the karma command line interface (cli) globally, which enable us to easily configure karma in our project
  • 15. nirkaufman@gmail.com $ karma init with the karma cli installed, we can create our configuration file fast and easy.
  • 16. nirkaufman@gmail.com $ karma start $ karma run Let`s take karma for a test drive: in webstorm, right click on the configuration file and choose run. if you don`t use webstorm, start the karma server with start, and run you tests with run
  • 17. nirkaufman@gmail.com quick intruduction to the Jasmine framwork Jasmine 101
  • 18. nirkaufman@gmail.com describe("suite name", function() { it("contains spec with an expectation", function() { expect(true).toBe(true); }); }); in jasmine, we begin by creating a test suite with the global describe function that wrap our specs. specs are defined by the global function it. inside the spec we can describe our expextations by using tha expect function chained to a matcher function
  • 19. nirkaufman@gmail.com describe("suite name", function() { beforeEach(function () {//excute before each spec}) it("contains spec with an expectation", function() { expect(true).toBe(true); }); afterEach(function () {//excute after each spec}) }); we can run code before and after each spec in a suite block using the beforeEach and afterEach functions
  • 20. nirkaufman@gmail.com // spy on the method setBar of foo object spyOn(foo, 'setBar'); it("contains spec with an expectation", function() { expect(foo.setBar).toHaveBeenCalled(); expect(foo.setBar).toHaveBeenCalledWith(32); }); }); jasmine use spies to track calls to a function with all it`s arguments. There are special matchers for interacting with spies. The toHaveBeenCalled and The toHaveBeenCalledWith
  • 21. nirkaufman@gmail.com Test Driven Development in practice Testing AngularJS
  • 22. nirkaufman@gmail.com $ bower install angular $ bower install angular-mocks We are going to develop a small Task Manger app. in the process we will learn how to unit test the building blocks of every AngularJS application: controllers, services, directives, events & http requests. First, let`s get some resources using bower
  • 24. nirkaufman@gmail.com // get the module that contain the controller beforeEach(module('todolist')); // inject the $controller and the rootScope beforeEach(inject(function ($rootScope, $controller) { // create a fresh new scope for the controller scope = $rootScope.$new(); // create a controller with this scope ctrl = $controller('TodoListController',{$scope: scope}); })); In order to test controllers we need to holds an instance of the controller, initialize a scope for it and testing our expectations against that scope.
  • 26. nirkaufman@gmail.com // get the module that contain the service beforeEach(module('todolist')); // inject the $injector beforeEach(inject(function ($injector) { // use the $injector to get a hold on the service service = $injector.get(‘ServiceName’); })); In order to test services we need to use the $injector to get an instance of the service
  • 28. nirkaufman@gmail.com // get the module that contain the service beforeEach(module('todolist')); // inject the $compile service and the $rootScope beforeEach(inject(function ($compile, $rootScope) { // use the $rootScope to create a scope for the directive scope = $rootScope; // create an angular element from a HTML string element = angular.element(‘<div my-directive ></div>’) // compile the element with the scope $compile(element)(scope) scope.$apply() })); In order to test a directive, we need to create an element that will host the directive and compile it with a scope. in our spec, we need trigger the digest.
  • 30. nirkaufman@gmail.com // inject the $httpBackend service and the $rootScope beforeEach(inject(function ($httpBackend) { // use the $rootScope to create a scope for the directive httpBackend = $httpBackend; it("somting that make a request", function() { // expect a request httpBackend.expectGET(‘api’).respond(200); // code that make a request httpBackend.flush(); // do`nt forget to flush.. }); })); the $httpBackend is a fake HTTP Back-end implementaion. in the most basic use we can verify that a request is made & stub responses
  • 32. nirkaufman@gmail.com When the number of test suites and specs grows larger, the overall test speed is affected. jasmine include some usfull syntax to control it. // run this usite ddescribe() // run this spec iit() // run this spec xit() webstorm users can install the ddescriber for jasmine
  • 33. nirkaufman@gmail.com in webstorm the run panel enable us some more featuers like: Set Auto Test Delay Time Export Test Results Filter and sort Run / Debug Configuration live templates
  • 34. nirkaufman@gmail.com Thank You! Download the reference project at: https://github.com/nirkaufman/angularjs-unit-testing-demo contact me at: nirkaufman@gmail.com or http://www.linkedin.com/in/nirkaufman