SlideShare ist ein Scribd-Unternehmen logo
1 von 32
describe("A suite: describe your tests", function () {
var foo;
beforeEach(function () {
foo = 0;
foo += 1;
});
afterEach(function () { foo = 0; });
it("Contains spec with an expectation", function () {
expect(foo).toEqual(1);
});
it("Can have more than one expectation", function () {
expect(foo).toEqual(1);
expect(true).toEqual(true);
});
});
it("Can contain any code", function () {
// actual == expected value
expect(value).toEqual(value);
});
 not.toEqual(val)
 not.toBe(val)
 not.toMatch(pattern)
 …
Every matcher's criteria can be inverted by
prepending .not:
beforeEach(function () {
jasmine.addMatchers({
toBeExponentiallyLessThan: function () {
return {
compare: function (actual, expected, scaleFactor) {
var result = {
pass: actual < (expected / (10 || scaleFactor))
};
//the success/failure messages
if (result.pass) {
result.message = actual +' is exponentially less than';
} else {
result.message = actual +' is not exponentially less than';
}
return result;
}
};
}
});
});
{ matcherName: fn =>
{ compare: fn => { pass: true | false, message : string }
describe("A spy", function () {
var foo, bar = null;
beforeEach(function () {
foo = {setBar: function (value) {bar = value;}};
spyOn(foo, 'setBar');
foo.setBar(123); // The bar == null
foo.setBar(456, 'another param'); // The bar == null
});
it("tracks that the spy was called", function () {
expect(foo.setBar).toHaveBeenCalled();
});
it("tracks all the arguments of its calls", function () {
expect(foo.setBar).toHaveBeenCalledWith(123);
expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
});
it("spy stops all execution on a function", function () {
expect(bar).toBeNull();
});
});
describe("A spy", function () {
var foo, bar = null;
beforeEach(function () {
foo = { setBar: function (value) {bar = value;} };
spyOn(foo, 'setBar');
});
it("tracks the arguments of all calls", function () {
foo.setBar(123);
foo.setBar(456, "baz");
expect(foo.setBar.calls.allArgs())
.toEqual([[123], [456, "baz"]]);
});
it("can provide the context and arguments to all calls", function () {
foo.setBar(123);
expect( foo.setBar.calls.all() )
.toEqual([{ object: foo, args: [123] }]);
});
});
describe("A spy", function () {
var foo, bar = null;
beforeEach(function () {
foo = {
setBar: function (value) {bar = value;}
};
spyOn(foo, 'setBar').and.callThrough();
});
it("can call through and then stub in the same spec", function () {
foo.setBar(123);
expect(bar).toEqual(123);
foo.setBar.and.stub();
bar = null;
foo.setBar(123);
expect(bar).toBe(null);
});
});
describe("Multiple spies, when created manually", function () {
var tape;
beforeEach(function () {
tape = jasmine.createSpyObj('tape', ['play', 'pause']);
tape.play();
tape.pause();
});
it("tracks that the spies were called", function () {
expect(tape.play).toHaveBeenCalled();
expect(tape.pause).toHaveBeenCalled();
});
});
<link href="jasmine.css" rel="stylesheet" />
<script src="jasmine.js"></script>
<script src="jasmine-html.js"></script>
<!– Angular Framework Modules -->
<script src="angular.js"></script>
<script src="angular-mocks.js"></script>
<!-- The Application Modules-->
<script src="app.js"></script>
<!-- The Specs Unit Testing -->
<script src="appSpec.js"></script>
<!-- use Jasmine to run and display test results -->
<script type="text/javascript">
var jasmineEnv = jasmine.getEnv();
jasmineEnv.addReporter( new jasmine.HtmlReporter() );
jasmineEnv.execute();
</script>
<link href="jasmine.css" rel="stylesheet" />
<script src="jasmine.js"></script>
<script src="jasmine-html.js"></script>
<!– Angular Framework Modules -->
<script src="angular.js"></script>
<script src="angular-mocks.js"></script>
<!-- The Application Modules-->
<script src="app.js"></script>
<!-- The Specs Unit Testing -->
<script src="appSpec.js"></script>
<!-- use Jasmine to run and display test results -->
<script type="text/javascript">
var jasmineEnv = jasmine.getEnv();
jasmineEnv.addReporter( new jasmine.HtmlReporter() );
jasmineEnv.execute();
</script>
describe('controllers', function () {
var $controller;
beforeEach( module('myApp.controllers') );
beforeEach( inject(function ( _$controller_ ) {
$controller = _$controller_;
}));
it('MyCtrl Spec', function () {
var myCtrl1 = $controller('MyCtrl1', { $scope: {} });
expect(myCtrl1).toBeDefined();
});
});
angular.module('async', [])
.factory('asyncGreeter', function ($timeout, $log) {
return {
say: function (name, timeout) {
$timeout(
function() {
$log.info("Hello," + name );
}, timeout );
}
};
});
describe('Async Greeter test', function () {
var asyncGreeter, $timeout, $log;
beforeEach(module('async'));
beforeEach(inject(function (_asyncGreeter_, _$timeout_, _$log_){
asyncGreeter = _asyncGreeter_;
$timeout = _$timeout_;
$log = _$log_;
}));
it('should greet the async World', function () {
asyncGreeter.say( 'World', 1000 * 100 );
$timeout.flush();
expect($log.info.logs).toContain(['Hello, World!']);
});
});
Request expectations Backend definitions
Syntax .expect(...).respond(...) .when(...).respond(...)
Typical usage strict unit tests loose unit testing
Fulfills multiple requests NO YES
Order of requests matters YES NO
Request required YES NO
Response required optional (see below) YES
myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
myAppDev.run(function ($httpBackend) {
phones = [{ name: 'phone1' }, { name: 'phone2' }];
// returns the current list of phones
$httpBackend.whenGET('/phones').respond(phones);
// adds a new phone to the phones array
$httpBackend.whenPOST('/phones').respond(function(method,url,data){
var phone = angular.fromJson(data);
phones.push(phone);
return [200, phone, {}];
});
$httpBackend.whenGET(/^/templates//).passThrough();
//...
});
AngularJS Testing
AngularJS Testing
AngularJS Testing

Weitere ähnliche Inhalte

Was ist angesagt?

Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6Riza Fahmi
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowKrzysztof Szafranek
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 
Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OBuzzcapture
 
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com GoTDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com Gotdc-globalcode
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
 
Javascript basics
Javascript basicsJavascript basics
Javascript basicsFin Chen
 
Unit testing with mocha
Unit testing with mochaUnit testing with mocha
Unit testing with mochaRevath S Kumar
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the ASTJarrod Overson
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionIan Barber
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersIan Barber
 
Refactoring to symfony components
Refactoring to symfony componentsRefactoring to symfony components
Refactoring to symfony componentsMichael Peacock
 
G*におけるソフトウェアテスト・シーズンIII
G*におけるソフトウェアテスト・シーズンIIIG*におけるソフトウェアテスト・シーズンIII
G*におけるソフトウェアテスト・シーズンIIITakuma Watabiki
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistAnton Arhipov
 

Was ist angesagt? (20)

Assignment
AssignmentAssignment
Assignment
 
Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. Now
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/O
 
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com GoTDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
The most exciting features of PHP 7.1
The most exciting features of PHP 7.1The most exciting features of PHP 7.1
The most exciting features of PHP 7.1
 
Unit testing with mocha
Unit testing with mochaUnit testing with mocha
Unit testing with mocha
 
C99
C99C99
C99
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
 
Lisp
LispLisp
Lisp
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
 
Sencha Touch Intro
Sencha Touch IntroSencha Touch Intro
Sencha Touch Intro
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find Fraudsters
 
Refactoring to symfony components
Refactoring to symfony componentsRefactoring to symfony components
Refactoring to symfony components
 
Ext oo
Ext ooExt oo
Ext oo
 
G*におけるソフトウェアテスト・シーズンIII
G*におけるソフトウェアテスト・シーズンIIIG*におけるソフトウェアテスト・シーズンIII
G*におけるソフトウェアテスト・シーズンIII
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
 

Andere mochten auch

AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesEyal Vardi
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS DirectivesEyal Vardi
 
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS RoutingEyal Vardi
 
Forms in AngularJS
Forms in AngularJSForms in AngularJS
Forms in AngularJSEyal Vardi
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
AngularJS Animations
AngularJS AnimationsAngularJS Animations
AngularJS AnimationsEyal Vardi
 
AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS OverviewEyal Vardi
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipesEyal Vardi
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScriptEyal Vardi
 
OOP in JavaScript
OOP in JavaScriptOOP in JavaScript
OOP in JavaScriptEyal Vardi
 
Planificación y organización de dominio
Planificación y organización de dominioPlanificación y organización de dominio
Planificación y organización de dominiolilidani103
 
Spa Architecture with Durandal and Friends
Spa Architecture with Durandal and FriendsSpa Architecture with Durandal and Friends
Spa Architecture with Durandal and FriendsJohnny Tordgeman
 
Testing Angular Applications - Jfokus 2017
Testing Angular Applications - Jfokus 2017Testing Angular Applications - Jfokus 2017
Testing Angular Applications - Jfokus 2017Matt Raible
 
Basics of angular directive (Part - 1)
Basics of angular directive (Part - 1)Basics of angular directive (Part - 1)
Basics of angular directive (Part - 1)Vijay Kani
 
Custom AngularJS Directives
Custom AngularJS DirectivesCustom AngularJS Directives
Custom AngularJS Directivesyprodev
 
AngularJS Custom Directives
AngularJS Custom DirectivesAngularJS Custom Directives
AngularJS Custom Directivesyprodev
 
AngularJS custom directive
AngularJS custom directiveAngularJS custom directive
AngularJS custom directiveNascenia IT
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introductionNir Kaufman
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile ProcessEyal Vardi
 

Andere mochten auch (20)

AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource Services
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
 
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS Routing
 
Forms in AngularJS
Forms in AngularJSForms in AngularJS
Forms in AngularJS
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
AngularJS Animations
AngularJS AnimationsAngularJS Animations
AngularJS Animations
 
AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS Overview
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipes
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScript
 
OOP in JavaScript
OOP in JavaScriptOOP in JavaScript
OOP in JavaScript
 
Planificación y organización de dominio
Planificación y organización de dominioPlanificación y organización de dominio
Planificación y organización de dominio
 
Spa Architecture with Durandal and Friends
Spa Architecture with Durandal and FriendsSpa Architecture with Durandal and Friends
Spa Architecture with Durandal and Friends
 
Testing Angular Applications - Jfokus 2017
Testing Angular Applications - Jfokus 2017Testing Angular Applications - Jfokus 2017
Testing Angular Applications - Jfokus 2017
 
Basics of angular directive (Part - 1)
Basics of angular directive (Part - 1)Basics of angular directive (Part - 1)
Basics of angular directive (Part - 1)
 
Custom AngularJS Directives
Custom AngularJS DirectivesCustom AngularJS Directives
Custom AngularJS Directives
 
AngularJS Custom Directives
AngularJS Custom DirectivesAngularJS Custom Directives
AngularJS Custom Directives
 
Nodejs
NodejsNodejs
Nodejs
 
AngularJS custom directive
AngularJS custom directiveAngularJS custom directive
AngularJS custom directive
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile Process
 

Ähnlich wie AngularJS Testing

JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineRaimonds Simanovskis
 
Test-driven JavaScript Development - OPITZ CONSULTING - Tobias Bosch - Stefa...
Test-driven JavaScript Development - OPITZ CONSULTING -  Tobias Bosch - Stefa...Test-driven JavaScript Development - OPITZ CONSULTING -  Tobias Bosch - Stefa...
Test-driven JavaScript Development - OPITZ CONSULTING - Tobias Bosch - Stefa...OPITZ CONSULTING Deutschland
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscexjeffz
 
Call stack, event loop and async programming
Call stack, event loop and async programmingCall stack, event loop and async programming
Call stack, event loop and async programmingMasters Academy
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)jeffz
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programmingjeffz
 
Unittesting JavaScript with Evidence
Unittesting JavaScript with EvidenceUnittesting JavaScript with Evidence
Unittesting JavaScript with EvidenceTobie Langel
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptjeffz
 
Implementing pattern-matching in JavaScript (full version)
Implementing pattern-matching in JavaScript (full version)Implementing pattern-matching in JavaScript (full version)
Implementing pattern-matching in JavaScript (full version)François-Guillaume Ribreau
 
04 Advanced Javascript
04 Advanced Javascript04 Advanced Javascript
04 Advanced Javascriptcrgwbr
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.jsWebsecurify
 
Javascript Common Mistakes
Javascript Common MistakesJavascript Common Mistakes
Javascript Common Mistakes동수 장
 
How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014Guillaume POTIER
 
20220112 sac v1
20220112 sac v120220112 sac v1
20220112 sac v1Sharon Liu
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVMRafael Winterhalter
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}.toster
 

Ähnlich wie AngularJS Testing (20)

JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 
Introduccion a Jasmin
Introduccion a JasminIntroduccion a Jasmin
Introduccion a Jasmin
 
Test-driven JavaScript Development - OPITZ CONSULTING - Tobias Bosch - Stefa...
Test-driven JavaScript Development - OPITZ CONSULTING -  Tobias Bosch - Stefa...Test-driven JavaScript Development - OPITZ CONSULTING -  Tobias Bosch - Stefa...
Test-driven JavaScript Development - OPITZ CONSULTING - Tobias Bosch - Stefa...
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
 
Call stack, event loop and async programming
Call stack, event loop and async programmingCall stack, event loop and async programming
Call stack, event loop and async programming
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
 
Unittesting JavaScript with Evidence
Unittesting JavaScript with EvidenceUnittesting JavaScript with Evidence
Unittesting JavaScript with Evidence
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
Implementing pattern-matching in JavaScript (full version)
Implementing pattern-matching in JavaScript (full version)Implementing pattern-matching in JavaScript (full version)
Implementing pattern-matching in JavaScript (full version)
 
04 Advanced Javascript
04 Advanced Javascript04 Advanced Javascript
04 Advanced Javascript
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.js
 
Javascript Common Mistakes
Javascript Common MistakesJavascript Common Mistakes
Javascript Common Mistakes
 
Testing with Node.js
Testing with Node.jsTesting with Node.js
Testing with Node.js
 
How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014
 
20220112 sac v1
20220112 sac v120220112 sac v1
20220112 sac v1
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Nevermore Unit Testing
Nevermore Unit TestingNevermore Unit Testing
Nevermore Unit Testing
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 

Mehr von Eyal Vardi

Smart Contract
Smart ContractSmart Contract
Smart ContractEyal Vardi
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2Eyal Vardi
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Eyal Vardi
 
Angular 2 NgModule
Angular 2 NgModuleAngular 2 NgModule
Angular 2 NgModuleEyal Vardi
 
Upgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.xUpgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.xEyal Vardi
 
Angular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time CompilationAngular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time CompilationEyal Vardi
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And NavigationEyal Vardi
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 ArchitectureEyal Vardi
 
Angular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.xAngular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.xEyal Vardi
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 ViewsEyal Vardi
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Eyal Vardi
 
Template syntax in Angular 2.0
Template syntax in Angular 2.0Template syntax in Angular 2.0
Template syntax in Angular 2.0Eyal Vardi
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0Eyal Vardi
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injectionEyal Vardi
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationEyal Vardi
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScriptEyal Vardi
 
Angular 2.0 Pipes
Angular 2.0 PipesAngular 2.0 Pipes
Angular 2.0 PipesEyal Vardi
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
 
Modules and injector
Modules and injectorModules and injector
Modules and injectorEyal Vardi
 

Mehr von Eyal Vardi (20)

Why magic
Why magicWhy magic
Why magic
 
Smart Contract
Smart ContractSmart Contract
Smart Contract
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)
 
Angular 2 NgModule
Angular 2 NgModuleAngular 2 NgModule
Angular 2 NgModule
 
Upgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.xUpgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.x
 
Angular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time CompilationAngular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time Compilation
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 Architecture
 
Angular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.xAngular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.x
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 Views
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
Template syntax in Angular 2.0
Template syntax in Angular 2.0Template syntax in Angular 2.0
Template syntax in Angular 2.0
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScript
 
Angular 2.0 Pipes
Angular 2.0 PipesAngular 2.0 Pipes
Angular 2.0 Pipes
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Modules and injector
Modules and injectorModules and injector
Modules and injector
 

Kürzlich hochgeladen

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 

Kürzlich hochgeladen (20)

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 

AngularJS Testing

  • 1.
  • 2.
  • 3.
  • 4.
  • 5. describe("A suite: describe your tests", function () { var foo; beforeEach(function () { foo = 0; foo += 1; }); afterEach(function () { foo = 0; }); it("Contains spec with an expectation", function () { expect(foo).toEqual(1); }); it("Can have more than one expectation", function () { expect(foo).toEqual(1); expect(true).toEqual(true); }); });
  • 6. it("Can contain any code", function () { // actual == expected value expect(value).toEqual(value); });
  • 7.  not.toEqual(val)  not.toBe(val)  not.toMatch(pattern)  … Every matcher's criteria can be inverted by prepending .not:
  • 8. beforeEach(function () { jasmine.addMatchers({ toBeExponentiallyLessThan: function () { return { compare: function (actual, expected, scaleFactor) { var result = { pass: actual < (expected / (10 || scaleFactor)) }; //the success/failure messages if (result.pass) { result.message = actual +' is exponentially less than'; } else { result.message = actual +' is not exponentially less than'; } return result; } }; } }); }); { matcherName: fn => { compare: fn => { pass: true | false, message : string }
  • 9.
  • 10. describe("A spy", function () { var foo, bar = null; beforeEach(function () { foo = {setBar: function (value) {bar = value;}}; spyOn(foo, 'setBar'); foo.setBar(123); // The bar == null foo.setBar(456, 'another param'); // The bar == null }); it("tracks that the spy was called", function () { expect(foo.setBar).toHaveBeenCalled(); }); it("tracks all the arguments of its calls", function () { expect(foo.setBar).toHaveBeenCalledWith(123); expect(foo.setBar).toHaveBeenCalledWith(456, 'another param'); }); it("spy stops all execution on a function", function () { expect(bar).toBeNull(); }); });
  • 11.
  • 12. describe("A spy", function () { var foo, bar = null; beforeEach(function () { foo = { setBar: function (value) {bar = value;} }; spyOn(foo, 'setBar'); }); it("tracks the arguments of all calls", function () { foo.setBar(123); foo.setBar(456, "baz"); expect(foo.setBar.calls.allArgs()) .toEqual([[123], [456, "baz"]]); }); it("can provide the context and arguments to all calls", function () { foo.setBar(123); expect( foo.setBar.calls.all() ) .toEqual([{ object: foo, args: [123] }]); }); });
  • 13.
  • 14. describe("A spy", function () { var foo, bar = null; beforeEach(function () { foo = { setBar: function (value) {bar = value;} }; spyOn(foo, 'setBar').and.callThrough(); }); it("can call through and then stub in the same spec", function () { foo.setBar(123); expect(bar).toEqual(123); foo.setBar.and.stub(); bar = null; foo.setBar(123); expect(bar).toBe(null); }); });
  • 15. describe("Multiple spies, when created manually", function () { var tape; beforeEach(function () { tape = jasmine.createSpyObj('tape', ['play', 'pause']); tape.play(); tape.pause(); }); it("tracks that the spies were called", function () { expect(tape.play).toHaveBeenCalled(); expect(tape.pause).toHaveBeenCalled(); }); });
  • 16. <link href="jasmine.css" rel="stylesheet" /> <script src="jasmine.js"></script> <script src="jasmine-html.js"></script> <!– Angular Framework Modules --> <script src="angular.js"></script> <script src="angular-mocks.js"></script> <!-- The Application Modules--> <script src="app.js"></script> <!-- The Specs Unit Testing --> <script src="appSpec.js"></script> <!-- use Jasmine to run and display test results --> <script type="text/javascript"> var jasmineEnv = jasmine.getEnv(); jasmineEnv.addReporter( new jasmine.HtmlReporter() ); jasmineEnv.execute(); </script>
  • 17. <link href="jasmine.css" rel="stylesheet" /> <script src="jasmine.js"></script> <script src="jasmine-html.js"></script> <!– Angular Framework Modules --> <script src="angular.js"></script> <script src="angular-mocks.js"></script> <!-- The Application Modules--> <script src="app.js"></script> <!-- The Specs Unit Testing --> <script src="appSpec.js"></script> <!-- use Jasmine to run and display test results --> <script type="text/javascript"> var jasmineEnv = jasmine.getEnv(); jasmineEnv.addReporter( new jasmine.HtmlReporter() ); jasmineEnv.execute(); </script>
  • 18.
  • 19.
  • 20. describe('controllers', function () { var $controller; beforeEach( module('myApp.controllers') ); beforeEach( inject(function ( _$controller_ ) { $controller = _$controller_; })); it('MyCtrl Spec', function () { var myCtrl1 = $controller('MyCtrl1', { $scope: {} }); expect(myCtrl1).toBeDefined(); }); });
  • 21. angular.module('async', []) .factory('asyncGreeter', function ($timeout, $log) { return { say: function (name, timeout) { $timeout( function() { $log.info("Hello," + name ); }, timeout ); } }; });
  • 22. describe('Async Greeter test', function () { var asyncGreeter, $timeout, $log; beforeEach(module('async')); beforeEach(inject(function (_asyncGreeter_, _$timeout_, _$log_){ asyncGreeter = _asyncGreeter_; $timeout = _$timeout_; $log = _$log_; })); it('should greet the async World', function () { asyncGreeter.say( 'World', 1000 * 100 ); $timeout.flush(); expect($log.info.logs).toContain(['Hello, World!']); }); });
  • 23.
  • 24.
  • 25.
  • 26.
  • 27. Request expectations Backend definitions Syntax .expect(...).respond(...) .when(...).respond(...) Typical usage strict unit tests loose unit testing Fulfills multiple requests NO YES Order of requests matters YES NO Request required YES NO Response required optional (see below) YES
  • 28.
  • 29. myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']); myAppDev.run(function ($httpBackend) { phones = [{ name: 'phone1' }, { name: 'phone2' }]; // returns the current list of phones $httpBackend.whenGET('/phones').respond(phones); // adds a new phone to the phones array $httpBackend.whenPOST('/phones').respond(function(method,url,data){ var phone = angular.fromJson(data); phones.push(phone); return [200, phone, {}]; }); $httpBackend.whenGET(/^/templates//).passThrough(); //... });