SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 
Refactoring to symfony components
Refactoring to symfony componentsRefactoring to symfony components
Refactoring to symfony components
Michael Peacock
 
G*におけるソフトウェアテスト・シーズンIII
G*におけるソフトウェアテスト・シーズンIIIG*におけるソフトウェアテスト・シーズンIII
G*におけるソフトウェアテスト・シーズンIII
Takuma Watabiki
 

Mais procurados (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
 

Destaque

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
lilidani103
 

Destaque (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
 

Semelhante a AngularJS Testing

深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
jeffz
 
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 Programming
jeffz
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
jeffz
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 

Semelhante a 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}
 

Mais de Eyal Vardi

Mais de 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
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Último (20)

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 

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(); //... });