SlideShare a Scribd company logo
Testing with AngularJS
Raissa Ferreira
rai200890@gmail.com
Testing Tools
● Testing Frameworks
○ Jasmine
● Karma (Unit Test)
● Grunt
● Protractor (E2E Test)
● Bower
● NVM
Testing Frameworks
● QUnit
● Jasmine
● Mocha
QUnit
Example 1
test('test', function() {
equals( {}, {}, 'fails, these are different objects');
});
Example 2
module('Module A');
test('a test',function() {});
test('an another test',
function() {});
module('Module B');
test('a test',
function() {});
test('an another test',
function() {});
Jasmine
Example
describe("A spec", function() {
var foo;
beforeEach(function() {
foo = 0;
foo += 1;
});
it("is just a function, so it can contain any code",function(){
expect(foo).toEqual(1);
});
});
Jasmine X QUnit
● Nested describes
● Less vulnerable to
changes, less setup
● Modules(can’t be
nested)
● Massive amount of
setup to cover all
different paths
Mocha
Example
var assert = require("assert")
describe('Array', function(){
describe('#indexOf()', function(){
it('should return -1 when the value is not present',
function(){
assert.equal(-1, [1,2,3].indexOf(5));
assert.equal(-1, [1,2,3].indexOf(0));
});
});
});
Jasmine X Mocha
● Runner
● Nested describes
● Built-in:
○ Assertion library
○ Mocking library
● Runner
● Nested describes
● You can choose:
○ Assertion library
(eg. Chai)
○ Mocking library
(eg. Sinon)
● Pick syntax
Jasmine
● Behavior Driven Development testing framework for
JavaScript
● Does not depend on any other JavaScript frameworks
● Does not require a DOM
● Clean syntax
Suites
● Begins with global Jasmine function describe
○ Takes two parameters:
■ string - a name or title for a spec suite, what is being
tested
■ function - Block of code that implements the suite
Jasmine
Specs
● Begins with global Jasmine function it.
○ Takes two parameters:
■ string - title of the spec
■ function - the spec, or test
○ Can contains one or more expectations
■ Expectation - assertion that is either true or false
○ Passing spec - all true expectations
○ Failing spec - one or more false expectations
Jasmine
Expectations
● Built with function expect
○ Takes the actual value
● Chained with a matcher function
○ Takes the expected value
Eg. expect(actualValue).toEqual(expectedValue);
Jasmine
Matchers
● Implement boolean comparison between actual and expected
value
● Responsible for reporting to Jasmine if expectation is true or
false
○ Based on this, Jasmine will pass or fail the spec
● Matcher can evaluate to a negative assertion by chaining the
call to expect with a not
Eg. expect(a).not.toBe(null);
Jasmine
Matchers
● Included Matchers
○ toBe(===), toEqual, toBeNull, toBeDefined, toBeUndefined
○ Boolean Casting - toBeFalsy, toBeTruthy
○ String/Regex - toMatch
○ Array - toContain
○ Math - toBeLessThen, toBeGreaterThan
○ Precision Math - toBeClose
○ Check if function throws exception - toThrow
Jasmine
Spies
● Test double functions
● Can stub any function
● Tracks calls to it and all arguments
● Only exists in describe and it blocks it is defined
■ Will be removed after each spec
● Matchers
■ toHaveBeenCalled - if the spy was called
■ toHaveBeenCalledWith - if argument list matches any of
the recorded calls to the spy
Jasmine
Jasmine
Asynchronous Support
● beforeEach, it and afterEach can take optional single
argument to be called when the async work is complete
Jasmine
Asynchronous Support
describe("Asynchronous specs", function() {
var value;
beforeEach(function(done) {
setTimeout(function() {
value=0;
done();
}, 1);
});
it("should support async execution of test preparation and
expectations", function(done) {
value++;
expect(value).toBeGreaterThan(0);
done();
});
});
ngMock
● Provides support to inject and mock Angular services into unit
tests
● Extends various core ng services
○ $exceptionHandler
○ $log
○ $interval
○ $httpBackend
○ $timeout
● Instalation (via Bower)
$ bower install angular-mocks --save-dev
ngMock
Functions (declared ONLY in jasmine or mocha)
● angular.mock.module
○ Registers a module configuration code
○ Collects configuration information to be used when the injector
is created by inject
● angular.mock.inject
○ Wraps a function into an injectable function
○ Creates new instance of $injector per test to be used for
resolving references
○ $injector is used to retrieve object instances as defined by
provider, instantiate types, invoke methods, and load modules
Unit Test (Service)
describe("Auth", function() {
beforeEach(module("app"));
var Auth, $httpBackend;
beforeEach(inject(function(_Auth_, _$httpBackend_) {
Auth = _Auth_;
$httpBackend = _$httpBackend_;
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingRequest();
});
Unit Test (Service)
describe(".logout", function() {
describe("given a valid token", function() {
var Session, token = "9664bbf375";
beforeEach(inject(function(_Session_) {
Session = _Session_;
$httpBackend.
whenGET("api/auth/logout.json?token="+token).
respond(200, { invalid: true });
spyOn(Session, "clear");
}));
it("should erase user’s token", function() {
Auth.logout(token);
$httpBackend.flush();/* explicitly flush pending requests */
expect(Session.clear).toHaveBeenCalled();
});
}); });
Unit Test (Controller)
describe("AuthController", function() {
beforeEach(module("app"));
var $scope, controller, $httpBackend;
beforeEach(inject(
function($controller, $injector, _$httpBackend_) {
$httpBackend = _$httpBackend_;
$scope = $injector.get("$rootScope").$new();
controller = $controller("AuthController",
{ $scope: $scope });
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingRequest();
});
Unit Test (Controller)
describe(".login", function() {
var $state, httpBackend;
describe("given valid user"s credentials", function() {
beforeEach(inject(function(_$state_) {
$state = _$state_;
$httpBackend.whenPOST("api/auth/login.json").respond(200,{});
spyOn($state, "go");
$scope.login();
$httpBackend.flush();
}));
it("should go to role selection state", function() {
expect($state.go).toHaveBeenCalledWith("role_selection");
});
});
}); });
Karma
● Testing Engine
○ Launches a HTTP server and generates the test
runner HTML file
■ Runs in browser
■ Can run in multiple real browsers (can also
run in a headless one - PhantomJS)
■ Show output in command line
■ Developed by the AngularJS team
Karma
● Instalation
# Install Karma:
$ npm install karma karma-cli --save-dev
# Install plugins that your project needs:
$ npm install karma-jasmine karma-phantomjs-launcher karma-
coverage karma-mocha-reporter --save-dev
● Configuration
# Initialize a config file:
$ node ./node_modules/karma-cli/bin/karma init [<configFile>]
Karma
● Configuration file ( karma.conf.js )
module.exports = function(config) {
config.set({
frameworks: ["jasmine"],
files: ["src/*.js","test/*.js"],
plugins: ["karma-jasmine","karma-phantomjs-launcher",
"karma-coverage","karma-mocha-reporter"],
browsers: ["PhantomJS"],
reporters: ["mocha","coverage"],
preprocessors: {"src/*.js": "coverage"},
coverageReporter: { type : "html", dir : "coverage"},
display: "full",
isVerbose: true,
showColors: true,
includeStackTrace: true
});
};
● Javascript Task Runner
● Automation of repetitive tasks:
○ Minification
○ Compilation
○ Unit Testing
...
● Instalation
# install Grunt
$ npm install grunt
# install Grunt’s command line interface globally
$ npm install -g grunt-cli
Grunt
● Gruntfile
grunt.initConfig({
...
unit: {
configFile: "karma.conf.js",
singleRun: true,
browsers: ["PhantomJS"]
}
});
...
grunt.loadNpmTasks("grunt-karma");
grunt.registerTask("unit", "Run unit test",["karma"]);
Grunt Task for Karma
Protractor
● Acceptance tests
● Integration Tests
● Main paths
● Takes longer to run(compared to unit testing)
● WebdriverJS (Binding for Selenium Webdriver)
● Works better with Jasmine
● Currently does not support PhantomJS
Protractor
API (Most Common functions)
● element Eg. element(locator)
○ isPresent
● element.all
● browser
○ waitForAngular
○ get
○ pause
○ debugger
API (Most Common functions)
● Protractor’s locators
○ by
■ binding
■ model
■ css
■ cssContainingText
■ buttonText
● getText
● sendKeys
● clear
● getAttribute
Protractor
Protractor
● Example
describe("angularjs homepage", function() {
it("should add one and two", function() {
browser.get("http://juliemr.github.io/protractor-
demo/");
element(by.model("first")).sendKeys(1);
element(by.model("second")).sendKeys(2);
element(by.id("gobutton")).click();
expect(element(by.binding("latest")).getText()).
toEqual("3");
});
});
});
ngMockE2E
● Fake HTTP backend implementation suitable for end-to-end testing
○ $httpBackend
● Can be used via:
● when API - when(<HTTPMETHOD>, url, params).respond
(statusCode, data)
○ shortcuts (whenGET, whenPOST,..)
● Can pass through requests to the real $httpBackend (passThrough
function)
● Flushes mocked out requests automatically
● Instalation (via Bower)
$ bower install angular-mocks --save-dev
● Instalation
# Install Protractor:
$ npm install protractor --save-dev
# Install webdriver-manager, helper tool to get an instance of a
Selenium Server running:
$ node node_modules/protractor/bin/webdriver-manager update
# Install Grunt Protractor Task
$ npm install grunt-protractor-runner --save-dev
# Install Rails Server Task
$ npm install grunt-rails-server--save-dev
Protractor
Protractor
● Configuration file(protractor.conf.js):
exports.config = {
capabilities: {
"browserName": "chrome"
},
directConnect: true, /* bypass selenium webdriver */
specs: ["spec/javascripts/e2e/**/*.js"],
baseUrl: "http://local.ntp.uff.br:4000",
framework: "jasmine"
}
● Gruntfile
grunt.initConfig({
...
rails: { /* Backend Task */
options: {
port: 4000,
environment: "test",
keepAlive: false
},
your_target: {
}
}
...
Grunt Task for Protractor
● Gruntfile
protractor: {
options: {
configFile: "node_modules/protractor/referenceConf.js",
keepAlive: false,
noColor: false,
},
your_target: {
options: {
configFile: "protractor.conf.js",
args: {}
}
}
}
Grunt Task for Protractor
● Gruntfile
...
grunt.loadNpmTasks("grunt-rails-server");
grunt.loadNpmTasks("grunt-protractor-runner");
...
grunt.registerTask("e2e", "Run e2e test",
["rails", "protractor"]);
Grunt Task for Protractor
NVM
● Instalation
# Install nvm (Node Version Manager)
$ curl https://raw.githubusercontent.com/creationix/nvm/v0.23.3
/install.sh | bash
# To source it from your shell, this line can be added to ~/.
bashrc, ~/.profile, or ~/.zshrc
$ source ~/.nvm/nvm.sh
# To install a node version
$ nvm install 0.10
# In your project folder, you can include a .nvmrc file to
choose the desired node version
$ nvm use 0.10
Bower
Package Manager for Web
● Instalation
# Install Bower globally
$ npm install -g bower
# Interactively create a bower.json file
$ bower init
# Install a package
$ bower install <package-name>
# List all installed packages and check for new versions
$ bower list
# Clean local unused packages
$ bower prune
Bower
● Configuration
bower.json
{
"name": "assets",
"dependencies": {
"jquery": "latest",
"bootstrap": "latest",
"angular": "1.3.4"
...
}
.bowerrc
{
"directory": "vendor/assets/bower_components"
}
Resources
Testing Frameworks
● QUnit
http://qunitjs.com/
● Jasmine
http://jasmine.github.io/2.2/introduction.html
● Mocha
http://mochajs.org/
Assertion library
● Chai
http://chaijs.com/
Mocking library
● Sinon
http://sinonjs.org/
Resources
Unit Testing
● Unit Testing
https://docs.angularjs.org/guide/unit-testing
● Jasmine
http://jasmine.github.io/2.2/introduction.html
● ngMock
https://docs.angularjs.org/api/ngMock
Resources
Test Runner
● Karma
http://karma-runner.github.io/
● Karma Jasmine
https://www.npmjs.com/package/karma-jasmine
● Karma PhantomJS Launcher
https://github.com/karma-runner/karma-phantomjs-launcher
● Karma Mocha Reporter
https://www.npmjs.com/package/karma-mocha-reporter
● Karma Coverage
https://github.com/karma-runner/karma-coverage
● PhantomJS
https://github.com/ariya/phantomjs
E2E Testing
● E2E Test
https://docs.angularjs.org/guide/e2e-testing
● Protractor
http://angular.github.io/protractor
● ngMockE2E
https://docs.angularjs.org/api/ngMockE2E
● HTTP Backend Proxy
https://www.npmjs.com/package/http-backend-proxy
Resources
Automate Tasks
● Grunt
http://gruntjs.com/
● Grunt Karma
https://github.com/karma-runner/grunt-karma
● Grunt Protractor Runner
https://www.npmjs.com/package/grunt-protractor-runner
Resources
Interesting Podcasts
● Adventures in Angular Podcast
http://devchat.tv/adventures-in-angular/026-aia-testing-tools
http://devchat.tv/adventures-in-angular/025-aia-testing-with-
ward-bell
Resources

More Related Content

What's hot (20)

ODP
Unit Testing and Coverage for AngularJS
Knoldus Inc.
 
PDF
Advanced Jasmine - Front-End JavaScript Unit Testing
Lars Thorup
 
PDF
JavaScript TDD with Jasmine and Karma
Christopher Bartling
 
PDF
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
PDF
Intro to testing Javascript with jasmine
Timothy Oxley
 
PDF
Quick tour to front end unit testing using jasmine
Gil Fink
 
PDF
AngularJS Unit Test
Chiew Carol
 
PPT
Testing in AngularJS
Peter Drinnan
 
PPTX
Angular Unit Testing
Avi Engelshtein
 
PPTX
AngularJS Unit Testing
Prince Norin
 
PPTX
Angular Unit Testing
Alessandro Giorgetti
 
PDF
Jasmine BDD for Javascript
Luis Alfredo Porras Páez
 
PDF
Karma - JS Test Runner
Sebastiano Armeli
 
ODP
Jquery- One slide completing all JQuery
Knoldus Inc.
 
PDF
Painless JavaScript Testing with Jest
Michał Pierzchała
 
PDF
Angular Unit Testing NDC Minn 2018
Justin James
 
PDF
Unit Testing JavaScript Applications
Ynon Perek
 
PPTX
jasmine
Asanka Indrajith
 
PDF
Client side unit tests - using jasmine & karma
Adam Klein
 
PDF
Unit Testing Express and Koa Middleware in ES2015
Morris Singer
 
Unit Testing and Coverage for AngularJS
Knoldus Inc.
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Lars Thorup
 
JavaScript TDD with Jasmine and Karma
Christopher Bartling
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
Intro to testing Javascript with jasmine
Timothy Oxley
 
Quick tour to front end unit testing using jasmine
Gil Fink
 
AngularJS Unit Test
Chiew Carol
 
Testing in AngularJS
Peter Drinnan
 
Angular Unit Testing
Avi Engelshtein
 
AngularJS Unit Testing
Prince Norin
 
Angular Unit Testing
Alessandro Giorgetti
 
Jasmine BDD for Javascript
Luis Alfredo Porras Páez
 
Karma - JS Test Runner
Sebastiano Armeli
 
Jquery- One slide completing all JQuery
Knoldus Inc.
 
Painless JavaScript Testing with Jest
Michał Pierzchała
 
Angular Unit Testing NDC Minn 2018
Justin James
 
Unit Testing JavaScript Applications
Ynon Perek
 
Client side unit tests - using jasmine & karma
Adam Klein
 
Unit Testing Express and Koa Middleware in ES2015
Morris Singer
 

Viewers also liked (16)

PPT
TDD, unit testing and java script testing frameworks workshop
Sikandar Ahmed
 
PPT
AngularJS Testing Strategies
njpst8
 
PDF
Angular 2 - What's new and what's different
Priscila Negreiros
 
KEY
Javascript Tests with Jasmine for Front-end Devs
Chris Powers
 
PDF
How To Use Dropbox
Jayson Ijalo
 
PDF
How To Use Dropbox
Ardanette Seguban
 
PPT
Testing Javascript with Jasmine
Tim Tyrrell
 
PDF
Phabricator gdg presentation
Nizameddin Ordulu
 
PPTX
JavaScript Unit Testing
L&T Technology Services Limited
 
PDF
Story about module management with angular.js
David Amend
 
PDF
EasyTest Test Automation Tool Introduction
Zhu Zhong
 
PPTX
Testing angular js
galan83
 
PPTX
Slaven tomac unit testing in angular js
Slaven Tomac
 
PDF
Test-Driven Development with TypeScript+Jasmine+AngularJS
SmartOrg
 
PDF
AngularJS Testing
Ahmed Elmehri
 
PPTX
TDD Basics with Angular.js and Jasmine
Luis Sánchez Castellanos
 
TDD, unit testing and java script testing frameworks workshop
Sikandar Ahmed
 
AngularJS Testing Strategies
njpst8
 
Angular 2 - What's new and what's different
Priscila Negreiros
 
Javascript Tests with Jasmine for Front-end Devs
Chris Powers
 
How To Use Dropbox
Jayson Ijalo
 
How To Use Dropbox
Ardanette Seguban
 
Testing Javascript with Jasmine
Tim Tyrrell
 
Phabricator gdg presentation
Nizameddin Ordulu
 
JavaScript Unit Testing
L&T Technology Services Limited
 
Story about module management with angular.js
David Amend
 
EasyTest Test Automation Tool Introduction
Zhu Zhong
 
Testing angular js
galan83
 
Slaven tomac unit testing in angular js
Slaven Tomac
 
Test-Driven Development with TypeScript+Jasmine+AngularJS
SmartOrg
 
AngularJS Testing
Ahmed Elmehri
 
TDD Basics with Angular.js and Jasmine
Luis Sánchez Castellanos
 
Ad

Similar to Angular testing (20)

PDF
Unit Testing Front End JavaScript
FITC
 
PDF
Developer Test - Things to Know
vilniusjug
 
PDF
E2E testing con nightwatch.js - Drupalcamp Spain 2018
Salvador Molina (Slv_)
 
PDF
Understanding JavaScript Testing
jeresig
 
PDF
Testing, Performance Analysis, and jQuery 1.4
jeresig
 
PDF
Testing in JavaScript
Digital Natives
 
PDF
Describe's Full of It's
Jim Lynch
 
PDF
Testing AngularJS
Jacopo Nardiello
 
PDF
Async JavaScript Unit Testing
Mihail Gaberov
 
PPTX
Testing Spring Applications
Muhammad Abdullah
 
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
PDF
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Fandy Gotama
 
PDF
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
Tech in Asia ID
 
PPTX
Unit testing
Pooya Sagharchiha
 
PDF
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
KEY
Unit testing en iOS @ MobileCon Galicia
Robot Media
 
PPT
An Introduction to AngularJs Unittesting
Inthra onsap
 
PDF
MT_01_unittest_python.pdf
Hans Jones
 
PDF
Java script object model
James Hsieh
 
PDF
Good Tests Bad Tests
Bild GmbH & Co. KG
 
Unit Testing Front End JavaScript
FITC
 
Developer Test - Things to Know
vilniusjug
 
E2E testing con nightwatch.js - Drupalcamp Spain 2018
Salvador Molina (Slv_)
 
Understanding JavaScript Testing
jeresig
 
Testing, Performance Analysis, and jQuery 1.4
jeresig
 
Testing in JavaScript
Digital Natives
 
Describe's Full of It's
Jim Lynch
 
Testing AngularJS
Jacopo Nardiello
 
Async JavaScript Unit Testing
Mihail Gaberov
 
Testing Spring Applications
Muhammad Abdullah
 
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Fandy Gotama
 
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
Tech in Asia ID
 
Unit testing
Pooya Sagharchiha
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
Unit testing en iOS @ MobileCon Galicia
Robot Media
 
An Introduction to AngularJs Unittesting
Inthra onsap
 
MT_01_unittest_python.pdf
Hans Jones
 
Java script object model
James Hsieh
 
Good Tests Bad Tests
Bild GmbH & Co. KG
 
Ad

Recently uploaded (20)

PPTX
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
 
PPTX
sajflsajfljsdfljslfjslfsdfas;fdsfksadfjlsdflkjslgfs;lfjlsajfl;sajfasfd.pptx
theknightme
 
PDF
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
PPT
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
DOCX
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
PDF
BRKACI-1001 - Your First 7 Days of ACI.pdf
fcesargonca
 
PPTX
PM200.pptxghjgfhjghjghjghjghjghjghjghjghjghj
breadpaan921
 
PDF
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
PPT
introduction to networking with basics coverage
RamananMuthukrishnan
 
PPTX
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
PDF
AI_MOD_1.pdf artificial intelligence notes
shreyarrce
 
PPTX
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
PPTX
internet básico presentacion es una red global
70965857
 
PDF
The Internet - By the numbers, presented at npNOG 11
APNIC
 
PDF
Azure_DevOps introduction for CI/CD and Agile
henrymails
 
PDF
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
PDF
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
PDF
Apple_Environmental_Progress_Report_2025.pdf
yiukwong
 
PPTX
Softuni - Psychology of entrepreneurship
Kalin Karakehayov
 
PPTX
原版西班牙莱昂大学毕业证(León毕业证书)如何办理
Taqyea
 
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
 
sajflsajfljsdfljslfjslfsdfas;fdsfksadfjlsdflkjslgfs;lfjlsajfl;sajfasfd.pptx
theknightme
 
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
BRKACI-1001 - Your First 7 Days of ACI.pdf
fcesargonca
 
PM200.pptxghjgfhjghjghjghjghjghjghjghjghjghj
breadpaan921
 
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
introduction to networking with basics coverage
RamananMuthukrishnan
 
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
AI_MOD_1.pdf artificial intelligence notes
shreyarrce
 
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
internet básico presentacion es una red global
70965857
 
The Internet - By the numbers, presented at npNOG 11
APNIC
 
Azure_DevOps introduction for CI/CD and Agile
henrymails
 
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
Apple_Environmental_Progress_Report_2025.pdf
yiukwong
 
Softuni - Psychology of entrepreneurship
Kalin Karakehayov
 
原版西班牙莱昂大学毕业证(León毕业证书)如何办理
Taqyea
 

Angular testing

  • 2. Testing Tools ● Testing Frameworks ○ Jasmine ● Karma (Unit Test) ● Grunt ● Protractor (E2E Test) ● Bower ● NVM
  • 4. QUnit Example 1 test('test', function() { equals( {}, {}, 'fails, these are different objects'); }); Example 2 module('Module A'); test('a test',function() {}); test('an another test', function() {}); module('Module B'); test('a test', function() {}); test('an another test', function() {});
  • 5. Jasmine Example describe("A spec", function() { var foo; beforeEach(function() { foo = 0; foo += 1; }); it("is just a function, so it can contain any code",function(){ expect(foo).toEqual(1); }); });
  • 6. Jasmine X QUnit ● Nested describes ● Less vulnerable to changes, less setup ● Modules(can’t be nested) ● Massive amount of setup to cover all different paths
  • 7. Mocha Example var assert = require("assert") describe('Array', function(){ describe('#indexOf()', function(){ it('should return -1 when the value is not present', function(){ assert.equal(-1, [1,2,3].indexOf(5)); assert.equal(-1, [1,2,3].indexOf(0)); }); }); });
  • 8. Jasmine X Mocha ● Runner ● Nested describes ● Built-in: ○ Assertion library ○ Mocking library ● Runner ● Nested describes ● You can choose: ○ Assertion library (eg. Chai) ○ Mocking library (eg. Sinon) ● Pick syntax
  • 9. Jasmine ● Behavior Driven Development testing framework for JavaScript ● Does not depend on any other JavaScript frameworks ● Does not require a DOM ● Clean syntax
  • 10. Suites ● Begins with global Jasmine function describe ○ Takes two parameters: ■ string - a name or title for a spec suite, what is being tested ■ function - Block of code that implements the suite Jasmine
  • 11. Specs ● Begins with global Jasmine function it. ○ Takes two parameters: ■ string - title of the spec ■ function - the spec, or test ○ Can contains one or more expectations ■ Expectation - assertion that is either true or false ○ Passing spec - all true expectations ○ Failing spec - one or more false expectations Jasmine
  • 12. Expectations ● Built with function expect ○ Takes the actual value ● Chained with a matcher function ○ Takes the expected value Eg. expect(actualValue).toEqual(expectedValue); Jasmine
  • 13. Matchers ● Implement boolean comparison between actual and expected value ● Responsible for reporting to Jasmine if expectation is true or false ○ Based on this, Jasmine will pass or fail the spec ● Matcher can evaluate to a negative assertion by chaining the call to expect with a not Eg. expect(a).not.toBe(null); Jasmine
  • 14. Matchers ● Included Matchers ○ toBe(===), toEqual, toBeNull, toBeDefined, toBeUndefined ○ Boolean Casting - toBeFalsy, toBeTruthy ○ String/Regex - toMatch ○ Array - toContain ○ Math - toBeLessThen, toBeGreaterThan ○ Precision Math - toBeClose ○ Check if function throws exception - toThrow Jasmine
  • 15. Spies ● Test double functions ● Can stub any function ● Tracks calls to it and all arguments ● Only exists in describe and it blocks it is defined ■ Will be removed after each spec ● Matchers ■ toHaveBeenCalled - if the spy was called ■ toHaveBeenCalledWith - if argument list matches any of the recorded calls to the spy Jasmine
  • 16. Jasmine Asynchronous Support ● beforeEach, it and afterEach can take optional single argument to be called when the async work is complete
  • 17. Jasmine Asynchronous Support describe("Asynchronous specs", function() { var value; beforeEach(function(done) { setTimeout(function() { value=0; done(); }, 1); }); it("should support async execution of test preparation and expectations", function(done) { value++; expect(value).toBeGreaterThan(0); done(); }); });
  • 18. ngMock ● Provides support to inject and mock Angular services into unit tests ● Extends various core ng services ○ $exceptionHandler ○ $log ○ $interval ○ $httpBackend ○ $timeout ● Instalation (via Bower) $ bower install angular-mocks --save-dev
  • 19. ngMock Functions (declared ONLY in jasmine or mocha) ● angular.mock.module ○ Registers a module configuration code ○ Collects configuration information to be used when the injector is created by inject ● angular.mock.inject ○ Wraps a function into an injectable function ○ Creates new instance of $injector per test to be used for resolving references ○ $injector is used to retrieve object instances as defined by provider, instantiate types, invoke methods, and load modules
  • 20. Unit Test (Service) describe("Auth", function() { beforeEach(module("app")); var Auth, $httpBackend; beforeEach(inject(function(_Auth_, _$httpBackend_) { Auth = _Auth_; $httpBackend = _$httpBackend_; })); afterEach(function() { $httpBackend.verifyNoOutstandingRequest(); });
  • 21. Unit Test (Service) describe(".logout", function() { describe("given a valid token", function() { var Session, token = "9664bbf375"; beforeEach(inject(function(_Session_) { Session = _Session_; $httpBackend. whenGET("api/auth/logout.json?token="+token). respond(200, { invalid: true }); spyOn(Session, "clear"); })); it("should erase user’s token", function() { Auth.logout(token); $httpBackend.flush();/* explicitly flush pending requests */ expect(Session.clear).toHaveBeenCalled(); }); }); });
  • 22. Unit Test (Controller) describe("AuthController", function() { beforeEach(module("app")); var $scope, controller, $httpBackend; beforeEach(inject( function($controller, $injector, _$httpBackend_) { $httpBackend = _$httpBackend_; $scope = $injector.get("$rootScope").$new(); controller = $controller("AuthController", { $scope: $scope }); })); afterEach(function() { $httpBackend.verifyNoOutstandingRequest(); });
  • 23. Unit Test (Controller) describe(".login", function() { var $state, httpBackend; describe("given valid user"s credentials", function() { beforeEach(inject(function(_$state_) { $state = _$state_; $httpBackend.whenPOST("api/auth/login.json").respond(200,{}); spyOn($state, "go"); $scope.login(); $httpBackend.flush(); })); it("should go to role selection state", function() { expect($state.go).toHaveBeenCalledWith("role_selection"); }); }); }); });
  • 24. Karma ● Testing Engine ○ Launches a HTTP server and generates the test runner HTML file ■ Runs in browser ■ Can run in multiple real browsers (can also run in a headless one - PhantomJS) ■ Show output in command line ■ Developed by the AngularJS team
  • 25. Karma ● Instalation # Install Karma: $ npm install karma karma-cli --save-dev # Install plugins that your project needs: $ npm install karma-jasmine karma-phantomjs-launcher karma- coverage karma-mocha-reporter --save-dev ● Configuration # Initialize a config file: $ node ./node_modules/karma-cli/bin/karma init [<configFile>]
  • 26. Karma ● Configuration file ( karma.conf.js ) module.exports = function(config) { config.set({ frameworks: ["jasmine"], files: ["src/*.js","test/*.js"], plugins: ["karma-jasmine","karma-phantomjs-launcher", "karma-coverage","karma-mocha-reporter"], browsers: ["PhantomJS"], reporters: ["mocha","coverage"], preprocessors: {"src/*.js": "coverage"}, coverageReporter: { type : "html", dir : "coverage"}, display: "full", isVerbose: true, showColors: true, includeStackTrace: true }); };
  • 27. ● Javascript Task Runner ● Automation of repetitive tasks: ○ Minification ○ Compilation ○ Unit Testing ... ● Instalation # install Grunt $ npm install grunt # install Grunt’s command line interface globally $ npm install -g grunt-cli Grunt
  • 28. ● Gruntfile grunt.initConfig({ ... unit: { configFile: "karma.conf.js", singleRun: true, browsers: ["PhantomJS"] } }); ... grunt.loadNpmTasks("grunt-karma"); grunt.registerTask("unit", "Run unit test",["karma"]); Grunt Task for Karma
  • 29. Protractor ● Acceptance tests ● Integration Tests ● Main paths ● Takes longer to run(compared to unit testing) ● WebdriverJS (Binding for Selenium Webdriver) ● Works better with Jasmine ● Currently does not support PhantomJS
  • 30. Protractor API (Most Common functions) ● element Eg. element(locator) ○ isPresent ● element.all ● browser ○ waitForAngular ○ get ○ pause ○ debugger
  • 31. API (Most Common functions) ● Protractor’s locators ○ by ■ binding ■ model ■ css ■ cssContainingText ■ buttonText ● getText ● sendKeys ● clear ● getAttribute Protractor
  • 32. Protractor ● Example describe("angularjs homepage", function() { it("should add one and two", function() { browser.get("http://juliemr.github.io/protractor- demo/"); element(by.model("first")).sendKeys(1); element(by.model("second")).sendKeys(2); element(by.id("gobutton")).click(); expect(element(by.binding("latest")).getText()). toEqual("3"); }); }); });
  • 33. ngMockE2E ● Fake HTTP backend implementation suitable for end-to-end testing ○ $httpBackend ● Can be used via: ● when API - when(<HTTPMETHOD>, url, params).respond (statusCode, data) ○ shortcuts (whenGET, whenPOST,..) ● Can pass through requests to the real $httpBackend (passThrough function) ● Flushes mocked out requests automatically ● Instalation (via Bower) $ bower install angular-mocks --save-dev
  • 34. ● Instalation # Install Protractor: $ npm install protractor --save-dev # Install webdriver-manager, helper tool to get an instance of a Selenium Server running: $ node node_modules/protractor/bin/webdriver-manager update # Install Grunt Protractor Task $ npm install grunt-protractor-runner --save-dev # Install Rails Server Task $ npm install grunt-rails-server--save-dev Protractor
  • 35. Protractor ● Configuration file(protractor.conf.js): exports.config = { capabilities: { "browserName": "chrome" }, directConnect: true, /* bypass selenium webdriver */ specs: ["spec/javascripts/e2e/**/*.js"], baseUrl: "http://local.ntp.uff.br:4000", framework: "jasmine" }
  • 36. ● Gruntfile grunt.initConfig({ ... rails: { /* Backend Task */ options: { port: 4000, environment: "test", keepAlive: false }, your_target: { } } ... Grunt Task for Protractor
  • 37. ● Gruntfile protractor: { options: { configFile: "node_modules/protractor/referenceConf.js", keepAlive: false, noColor: false, }, your_target: { options: { configFile: "protractor.conf.js", args: {} } } } Grunt Task for Protractor
  • 39. NVM ● Instalation # Install nvm (Node Version Manager) $ curl https://raw.githubusercontent.com/creationix/nvm/v0.23.3 /install.sh | bash # To source it from your shell, this line can be added to ~/. bashrc, ~/.profile, or ~/.zshrc $ source ~/.nvm/nvm.sh # To install a node version $ nvm install 0.10 # In your project folder, you can include a .nvmrc file to choose the desired node version $ nvm use 0.10
  • 40. Bower Package Manager for Web ● Instalation # Install Bower globally $ npm install -g bower # Interactively create a bower.json file $ bower init # Install a package $ bower install <package-name> # List all installed packages and check for new versions $ bower list # Clean local unused packages $ bower prune
  • 41. Bower ● Configuration bower.json { "name": "assets", "dependencies": { "jquery": "latest", "bootstrap": "latest", "angular": "1.3.4" ... } .bowerrc { "directory": "vendor/assets/bower_components" }
  • 42. Resources Testing Frameworks ● QUnit http://qunitjs.com/ ● Jasmine http://jasmine.github.io/2.2/introduction.html ● Mocha http://mochajs.org/ Assertion library ● Chai http://chaijs.com/ Mocking library ● Sinon http://sinonjs.org/
  • 43. Resources Unit Testing ● Unit Testing https://docs.angularjs.org/guide/unit-testing ● Jasmine http://jasmine.github.io/2.2/introduction.html ● ngMock https://docs.angularjs.org/api/ngMock
  • 44. Resources Test Runner ● Karma http://karma-runner.github.io/ ● Karma Jasmine https://www.npmjs.com/package/karma-jasmine ● Karma PhantomJS Launcher https://github.com/karma-runner/karma-phantomjs-launcher ● Karma Mocha Reporter https://www.npmjs.com/package/karma-mocha-reporter ● Karma Coverage https://github.com/karma-runner/karma-coverage ● PhantomJS https://github.com/ariya/phantomjs
  • 45. E2E Testing ● E2E Test https://docs.angularjs.org/guide/e2e-testing ● Protractor http://angular.github.io/protractor ● ngMockE2E https://docs.angularjs.org/api/ngMockE2E ● HTTP Backend Proxy https://www.npmjs.com/package/http-backend-proxy Resources
  • 46. Automate Tasks ● Grunt http://gruntjs.com/ ● Grunt Karma https://github.com/karma-runner/grunt-karma ● Grunt Protractor Runner https://www.npmjs.com/package/grunt-protractor-runner Resources
  • 47. Interesting Podcasts ● Adventures in Angular Podcast http://devchat.tv/adventures-in-angular/026-aia-testing-tools http://devchat.tv/adventures-in-angular/025-aia-testing-with- ward-bell Resources