SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
Javascript
Testing
Jasmine, Chai, and Phantom
by Brandon D'Imperio
Developers test more than
enough, right?
● Our quality is so high, we don't need to test.
● We don't have dedicated testers
● Our testers find everything just fine.
● Where we're going we don't need roads. -
Doc
Manual testing is the way
to go
● They remember to test everything every time
a change is made, right?
● Manual testing is fun, fast, and enjoyable.
I don't always test
Yay Coding!
Really, coding?
Jasmine testing is coding
Ok, maybe scripting, but
almost coding!
You get testing, while
your developers get to
keep coding.
Enter Jasmine
No, not this one
JasmineJs
BDD for your JavaScript
Jasmine is a behavior-driven development framework for testing your JavaScript code. It does not depend on any other JavaScript
frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests.
describe("Jasmine", function() {
it("makes testing JavaScript awesome!", function() {
expect(yourCode).toBeLotsBetter();
});
});
Start Jasmine
(function () {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 250;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function (spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
document.querySelector('.version').innerHTML = jasmineEnv.versionString();
execJasmine();
};
function execJasmine() {
console.log("running jasmine");
jasmineEnv.execute();
}
})();
Chai
Assertion framework
var assert = require('chai').assert
, foo = 'bar'
, beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };
assert.typeOf(foo, 'string', 'foo is a string');
assert.equal(foo, 'bar', 'foo equal `bar`');
assert.lengthOf(foo, 3, 'foo`s value has a length of 3');
assert.lengthOf(beverages.tea, 3, 'beverages has 3 types
of tea');
Or
var expect = require('chai').expect
, foo = 'bar'
, beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };
expect(foo).to.be.a('string');
expect(foo).to.equal('bar');
expect(foo).to.have.length(3);
expect(beverages).to.have.property('tea').with.length(3);
Or
var should = require('chai').should() //actually call the
the function
, foo = 'bar'
, beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };
foo.should.be.a('string');
foo.should.equal('bar');
foo.should.have.length(3);
beverages.should.have.property('tea').with.length
(3);
PhantomJs
Is your automated testing not quite fast
enough?
Automated testing tools not quite extensible
enough?
Try PhantomJs
Full web stack
No browser required
Phantom Barebones
example
console.log('Loading a web page');
var page = require('webpage').create();
var url = 'http://www.phantomjs.org/';
page.open(url, function (status) {
//Page is loaded!
phantom.exit();
});
Phantom Sample Post
// Example using HTTP POST operation
var page = require('webpage').create(),
server = 'http://posttestserver.com/post.php?dump',
data = 'universe=expanding&answer=42';
page.open(server, 'post', data, function (status) {
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log(page.content);
}
phantom.exit();
});
Phantom Sample - Render
to image
var page = require('webpage').create();
page.viewportSize = { width: 400, height : 400 };
page.content = '<html><body><canvas id="surface"></canvas></body></html>';
page.evaluate(function() {
var el = document.getElementById('surface'),
context = el.getContext('2d'),
width = window.innerWidth,
height = window.innerHeight,
cx = width / 2,
cy = height / 2,
radius = width / 2.3,
imageData,
pixels,
hue, sat, value,
i = 0, x, y, rx, ry, d,
f, g, p, u, v, w, rgb;
el.width = width;
el.height = height;
imageData = context.createImageData(width, height);
pixels = imageData.data;
Phantom Sample - Render
to image(cont.)
for (y = 0; y < height; y = y + 1) {
for (x = 0; x < width; x = x + 1, i = i + 4) {
rx = x - cx;
ry = y - cy;
d = rx * rx + ry * ry;
if (d < radius * radius) {
hue = 6 * (Math.atan2(ry, rx) + Math.PI) / (2 * Math.PI);
sat = Math.sqrt(d) / radius;
g = Math.floor(hue);
f = hue - g;
u = 255 * (1 - sat);
v = 255 * (1 - sat * f);
w = 255 * (1 - sat * (1 - f));
pixels[i] = [255, v, u, u, w, 255, 255][g];
pixels[i + 1] = [w, 255, 255, v, u, u, w][g];
pixels[i + 2] = [u, u, w, 255, 255, v, u][g];
pixels[i + 3] = 255;
}
}
}
context.putImageData(imageData, 0, 0);
document.body.style.backgroundColor = 'white';
document.body.style.margin = '0px';
});
page.render('colorwheel.png');
phantom.exit();
PhantomJs+Chai
phantom.injectJs("chai.js");
var assert = chai.assert;
var expect = chai.expect;
var bAssert = function(delegate, onError, onSuccess) {
success = false;
try {
delegate();
success = true;
} catch (err) {
//chai delegate failed
if (onError) {
onError(err);
} else {
if (bNavigator.config.attemptToLogAssertCaller) {
var callerNameMatch = bAssert.caller.toString().match(/function
([^(]+)/);
if (callerNameMatch && callerNameMatch[1]) {
console.error('<chai>' + err + '<caller>' + callerNameMatch[1] +
'</caller></chai>');
} else console.error('<chai>' + err + '<callerunknown /></chai>');
//console.log('caller was '+ callerNameMatch[1]);
} else {
console.error('<chai>' + err + '</chai>');
}
}
} //end catch
if (success === true && onSuccess) {
onSuccess();
}
};
My Chai (not Mai-Tai)
bAssert(function(){ assert.typeOf('test','string','test is a string');});
bAssert(function(){
var currentItemIndex=page.evaluate(function(){
return $('.first-index:first').text();
});
console.log('currentItemIndex='+currentItemIndex);
assert.notEqual(currentItemIndex,'','current item index should never be empty');
});
References
http://pivotal.github.io/jasmine/
http://chaijs.com/
http://phantomjs.org/
Mine:
http://jsfiddle.net/Maslow/V8ryc/show
http://jsfiddle.net/Maslow/66MJU/show/
https://github.com/ImaginaryDevelopment/javascript/tree/master/phantom
These slides
http://j.mp/13spNkW
Topics Available
● Meta-Programming
○ T4
○ CoffeeScript
● Javascript Topics
○ Knockout
■ Custom bindings
■ KoGrid
■ jQuery
● ALM
○ TFS - Custom Workflow builds
○ SonarSource Code quality analysis
● Functional Programming
More topics
● Unit testing
● Entity Framework
● Dependency Injection
● Asp.Net MVC4
● MvcOData
○ Knockout -> OdataUrl Generation -> Ajax -> MVC ->
WCF Data services -> Entity Framework
Me
http://stackoverflow.com/users/57883/maslow
imaginarydevelopment @ gmail

Contenu connexe

Tendances

Jasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyJasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyIgor Napierala
 
GeoScript - Spatial Capabilities for Scripting Languages
GeoScript - Spatial Capabilities for Scripting LanguagesGeoScript - Spatial Capabilities for Scripting Languages
GeoScript - Spatial Capabilities for Scripting LanguagesJustin Deoliveira
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaExoLeaders.com
 
Scripting GeoServer with GeoScript
Scripting GeoServer with GeoScriptScripting GeoServer with GeoScript
Scripting GeoServer with GeoScriptJustin Deoliveira
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Roy Yu
 
Testing JavaScript Applications
Testing JavaScript ApplicationsTesting JavaScript Applications
Testing JavaScript ApplicationsThe Rolling Scopes
 
Zero to Testing in JavaScript
Zero to Testing in JavaScriptZero to Testing in JavaScript
Zero to Testing in JavaScriptpamselle
 
NoSQL Injections in Node.js - The case of MongoDB
NoSQL Injections in Node.js - The case of MongoDBNoSQL Injections in Node.js - The case of MongoDB
NoSQL Injections in Node.js - The case of MongoDBSqreen
 
Relaxing With CouchDB
Relaxing With CouchDBRelaxing With CouchDB
Relaxing With CouchDBleinweber
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.jsWebsecurify
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2rubyMarc Chung
 
CSSO – compress CSS (english version)
CSSO – compress CSS (english version)CSSO – compress CSS (english version)
CSSO – compress CSS (english version)Roman Dvornov
 
Svcc Java2D And Groovy
Svcc Java2D And GroovySvcc Java2D And Groovy
Svcc Java2D And GroovyAndres Almiray
 
Idiomatic spock
Idiomatic spockIdiomatic spock
Idiomatic spockGR8Conf
 
TRICK2015 results
TRICK2015 resultsTRICK2015 results
TRICK2015 resultsmametter
 

Tendances (19)

Jasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyJasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishy
 
GeoScript - Spatial Capabilities for Scripting Languages
GeoScript - Spatial Capabilities for Scripting LanguagesGeoScript - Spatial Capabilities for Scripting Languages
GeoScript - Spatial Capabilities for Scripting Languages
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
 
Scripting GeoServer with GeoScript
Scripting GeoServer with GeoScriptScripting GeoServer with GeoScript
Scripting GeoServer with GeoScript
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101
 
The State of GeoServer
The State of GeoServerThe State of GeoServer
The State of GeoServer
 
Testing JavaScript Applications
Testing JavaScript ApplicationsTesting JavaScript Applications
Testing JavaScript Applications
 
Zero to Testing in JavaScript
Zero to Testing in JavaScriptZero to Testing in JavaScript
Zero to Testing in JavaScript
 
NoSQL Injections in Node.js - The case of MongoDB
NoSQL Injections in Node.js - The case of MongoDBNoSQL Injections in Node.js - The case of MongoDB
NoSQL Injections in Node.js - The case of MongoDB
 
Relaxing With CouchDB
Relaxing With CouchDBRelaxing With CouchDB
Relaxing With CouchDB
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.js
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2ruby
 
3 u-mpb2u2na
 3 u-mpb2u2na 3 u-mpb2u2na
3 u-mpb2u2na
 
CSSO – compress CSS (english version)
CSSO – compress CSS (english version)CSSO – compress CSS (english version)
CSSO – compress CSS (english version)
 
Svcc Java2D And Groovy
Svcc Java2D And GroovySvcc Java2D And Groovy
Svcc Java2D And Groovy
 
Jasmine BDD for Javascript
Jasmine BDD for JavascriptJasmine BDD for Javascript
Jasmine BDD for Javascript
 
Idiomatic spock
Idiomatic spockIdiomatic spock
Idiomatic spock
 
Djangocon
DjangoconDjangocon
Djangocon
 
TRICK2015 results
TRICK2015 resultsTRICK2015 results
TRICK2015 results
 

En vedette

Василевский Илья (Fun-box): "автоматизация браузера при помощи PhantomJS"
Василевский Илья (Fun-box): "автоматизация браузера при помощи PhantomJS"Василевский Илья (Fun-box): "автоматизация браузера при помощи PhantomJS"
Василевский Илья (Fun-box): "автоматизация браузера при помощи PhantomJS"Provectus
 
Superfast Automated Web Testing with CasperJS & PhantomJS
Superfast Automated Web Testing with CasperJS & PhantomJS Superfast Automated Web Testing with CasperJS & PhantomJS
Superfast Automated Web Testing with CasperJS & PhantomJS Hervé Vũ Roussel
 
Phantom js quick start
Phantom js quick startPhantom js quick start
Phantom js quick startji guang
 
Introduction to PhantomJS
Introduction to PhantomJSIntroduction to PhantomJS
Introduction to PhantomJSErol Selitektay
 
An introduction to PhantomJS: A headless browser for automation test.
An introduction to PhantomJS: A headless browser for automation test.An introduction to PhantomJS: A headless browser for automation test.
An introduction to PhantomJS: A headless browser for automation test.BugRaptors
 
Automated Testing with Cucumber, PhantomJS and Selenium
Automated Testing with Cucumber, PhantomJS and SeleniumAutomated Testing with Cucumber, PhantomJS and Selenium
Automated Testing with Cucumber, PhantomJS and SeleniumDev9Com
 
The Mobile Story 2016 [Infographic]
The Mobile Story 2016 [Infographic]The Mobile Story 2016 [Infographic]
The Mobile Story 2016 [Infographic]Ajeet Singh
 

En vedette (7)

Василевский Илья (Fun-box): "автоматизация браузера при помощи PhantomJS"
Василевский Илья (Fun-box): "автоматизация браузера при помощи PhantomJS"Василевский Илья (Fun-box): "автоматизация браузера при помощи PhantomJS"
Василевский Илья (Fun-box): "автоматизация браузера при помощи PhantomJS"
 
Superfast Automated Web Testing with CasperJS & PhantomJS
Superfast Automated Web Testing with CasperJS & PhantomJS Superfast Automated Web Testing with CasperJS & PhantomJS
Superfast Automated Web Testing with CasperJS & PhantomJS
 
Phantom js quick start
Phantom js quick startPhantom js quick start
Phantom js quick start
 
Introduction to PhantomJS
Introduction to PhantomJSIntroduction to PhantomJS
Introduction to PhantomJS
 
An introduction to PhantomJS: A headless browser for automation test.
An introduction to PhantomJS: A headless browser for automation test.An introduction to PhantomJS: A headless browser for automation test.
An introduction to PhantomJS: A headless browser for automation test.
 
Automated Testing with Cucumber, PhantomJS and Selenium
Automated Testing with Cucumber, PhantomJS and SeleniumAutomated Testing with Cucumber, PhantomJS and Selenium
Automated Testing with Cucumber, PhantomJS and Selenium
 
The Mobile Story 2016 [Infographic]
The Mobile Story 2016 [Infographic]The Mobile Story 2016 [Infographic]
The Mobile Story 2016 [Infographic]
 

Similaire à Js testing

Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...BradNeuberg
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend TestingNeil Crosby
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineAndy McKay
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
 
Developer Tests - Things to Know
Developer Tests - Things to KnowDeveloper Tests - Things to Know
Developer Tests - Things to KnowVaidas Pilkauskas
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETBen Hall
 
Scti 2011 minicurso jquery
Scti 2011 minicurso jqueryScti 2011 minicurso jquery
Scti 2011 minicurso jqueryciberglo
 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaRobot Media
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with WingsRemy Sharp
 
An Introduction To jQuery
An Introduction To jQueryAn Introduction To jQuery
An Introduction To jQueryAndy Gibson
 
Танки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
Танки_в_Лунапарке: нагрузочное_тестирование_в_ЯндексеТанки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
Танки_в_Лунапарке: нагрузочное_тестирование_в_ЯндексеYandex
 
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
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformationLars Marius Garshol
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testingVisual Engineering
 
Testing JavaScript with Jasmine in Rails Applications
Testing JavaScript with Jasmine in Rails Applications Testing JavaScript with Jasmine in Rails Applications
Testing JavaScript with Jasmine in Rails Applications Hector Correa
 

Similaire à Js testing (20)

Fantom and Tales
Fantom and TalesFantom and Tales
Fantom and Tales
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
Performance patterns
Performance patternsPerformance patterns
Performance patterns
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Lettering js
Lettering jsLettering js
Lettering js
 
Developer Tests - Things to Know
Developer Tests - Things to KnowDeveloper Tests - Things to Know
Developer Tests - Things to Know
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NET
 
Scti 2011 minicurso jquery
Scti 2011 minicurso jqueryScti 2011 minicurso jquery
Scti 2011 minicurso jquery
 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon Galicia
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with Wings
 
An Introduction To jQuery
An Introduction To jQueryAn Introduction To jQuery
An Introduction To jQuery
 
Танки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
Танки_в_Лунапарке: нагрузочное_тестирование_в_ЯндексеТанки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
Танки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
 
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
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
Testing JavaScript with Jasmine in Rails Applications
Testing JavaScript with Jasmine in Rails Applications Testing JavaScript with Jasmine in Rails Applications
Testing JavaScript with Jasmine in Rails Applications
 

Plus de MaslowB

F# for BLOBA, by brandon d'imperio
F# for BLOBA, by brandon d'imperioF# for BLOBA, by brandon d'imperio
F# for BLOBA, by brandon d'imperioMaslowB
 
Knockout vs. angular
Knockout vs. angularKnockout vs. angular
Knockout vs. angularMaslowB
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolatorMaslowB
 
What’s new mvc 4
What’s new mvc 4What’s new mvc 4
What’s new mvc 4MaslowB
 
A clean repository pattern in ef
A clean repository pattern in efA clean repository pattern in ef
A clean repository pattern in efMaslowB
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolatorMaslowB
 
Mvc presentation
Mvc presentationMvc presentation
Mvc presentationMaslowB
 
Metaprogramming by brandon
Metaprogramming by brandonMetaprogramming by brandon
Metaprogramming by brandonMaslowB
 

Plus de MaslowB (9)

F# for BLOBA, by brandon d'imperio
F# for BLOBA, by brandon d'imperioF# for BLOBA, by brandon d'imperio
F# for BLOBA, by brandon d'imperio
 
Knockout vs. angular
Knockout vs. angularKnockout vs. angular
Knockout vs. angular
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolator
 
What’s new mvc 4
What’s new mvc 4What’s new mvc 4
What’s new mvc 4
 
A clean repository pattern in ef
A clean repository pattern in efA clean repository pattern in ef
A clean repository pattern in ef
 
Metrics
MetricsMetrics
Metrics
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolator
 
Mvc presentation
Mvc presentationMvc presentation
Mvc presentation
 
Metaprogramming by brandon
Metaprogramming by brandonMetaprogramming by brandon
Metaprogramming by brandon
 

Dernier

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Dernier (20)

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Js testing

  • 1. Javascript Testing Jasmine, Chai, and Phantom by Brandon D'Imperio
  • 2. Developers test more than enough, right? ● Our quality is so high, we don't need to test. ● We don't have dedicated testers ● Our testers find everything just fine. ● Where we're going we don't need roads. - Doc
  • 3. Manual testing is the way to go ● They remember to test everything every time a change is made, right? ● Manual testing is fun, fast, and enjoyable.
  • 6. Jasmine testing is coding Ok, maybe scripting, but almost coding! You get testing, while your developers get to keep coding.
  • 8. JasmineJs BDD for your JavaScript Jasmine is a behavior-driven development framework for testing your JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests. describe("Jasmine", function() { it("makes testing JavaScript awesome!", function() { expect(yourCode).toBeLotsBetter(); }); });
  • 9. Start Jasmine (function () { var jasmineEnv = jasmine.getEnv(); jasmineEnv.updateInterval = 250; var htmlReporter = new jasmine.HtmlReporter(); jasmineEnv.addReporter(htmlReporter); jasmineEnv.specFilter = function (spec) { return htmlReporter.specFilter(spec); }; var currentWindowOnload = window.onload; window.onload = function() { if (currentWindowOnload) { currentWindowOnload(); } document.querySelector('.version').innerHTML = jasmineEnv.versionString(); execJasmine(); }; function execJasmine() { console.log("running jasmine"); jasmineEnv.execute(); } })();
  • 10. Chai Assertion framework var assert = require('chai').assert , foo = 'bar' , beverages = { tea: [ 'chai', 'matcha', 'oolong' ] }; assert.typeOf(foo, 'string', 'foo is a string'); assert.equal(foo, 'bar', 'foo equal `bar`'); assert.lengthOf(foo, 3, 'foo`s value has a length of 3'); assert.lengthOf(beverages.tea, 3, 'beverages has 3 types of tea'); Or var expect = require('chai').expect , foo = 'bar' , beverages = { tea: [ 'chai', 'matcha', 'oolong' ] }; expect(foo).to.be.a('string'); expect(foo).to.equal('bar'); expect(foo).to.have.length(3); expect(beverages).to.have.property('tea').with.length(3); Or var should = require('chai').should() //actually call the the function , foo = 'bar' , beverages = { tea: [ 'chai', 'matcha', 'oolong' ] }; foo.should.be.a('string'); foo.should.equal('bar'); foo.should.have.length(3); beverages.should.have.property('tea').with.length (3);
  • 11. PhantomJs Is your automated testing not quite fast enough? Automated testing tools not quite extensible enough? Try PhantomJs Full web stack No browser required
  • 12. Phantom Barebones example console.log('Loading a web page'); var page = require('webpage').create(); var url = 'http://www.phantomjs.org/'; page.open(url, function (status) { //Page is loaded! phantom.exit(); });
  • 13. Phantom Sample Post // Example using HTTP POST operation var page = require('webpage').create(), server = 'http://posttestserver.com/post.php?dump', data = 'universe=expanding&answer=42'; page.open(server, 'post', data, function (status) { if (status !== 'success') { console.log('Unable to post!'); } else { console.log(page.content); } phantom.exit(); });
  • 14. Phantom Sample - Render to image var page = require('webpage').create(); page.viewportSize = { width: 400, height : 400 }; page.content = '<html><body><canvas id="surface"></canvas></body></html>'; page.evaluate(function() { var el = document.getElementById('surface'), context = el.getContext('2d'), width = window.innerWidth, height = window.innerHeight, cx = width / 2, cy = height / 2, radius = width / 2.3, imageData, pixels, hue, sat, value, i = 0, x, y, rx, ry, d, f, g, p, u, v, w, rgb; el.width = width; el.height = height; imageData = context.createImageData(width, height); pixels = imageData.data;
  • 15. Phantom Sample - Render to image(cont.) for (y = 0; y < height; y = y + 1) { for (x = 0; x < width; x = x + 1, i = i + 4) { rx = x - cx; ry = y - cy; d = rx * rx + ry * ry; if (d < radius * radius) { hue = 6 * (Math.atan2(ry, rx) + Math.PI) / (2 * Math.PI); sat = Math.sqrt(d) / radius; g = Math.floor(hue); f = hue - g; u = 255 * (1 - sat); v = 255 * (1 - sat * f); w = 255 * (1 - sat * (1 - f)); pixels[i] = [255, v, u, u, w, 255, 255][g]; pixels[i + 1] = [w, 255, 255, v, u, u, w][g]; pixels[i + 2] = [u, u, w, 255, 255, v, u][g]; pixels[i + 3] = 255; } } } context.putImageData(imageData, 0, 0); document.body.style.backgroundColor = 'white'; document.body.style.margin = '0px'; }); page.render('colorwheel.png'); phantom.exit();
  • 16. PhantomJs+Chai phantom.injectJs("chai.js"); var assert = chai.assert; var expect = chai.expect; var bAssert = function(delegate, onError, onSuccess) { success = false; try { delegate(); success = true; } catch (err) { //chai delegate failed if (onError) { onError(err); } else { if (bNavigator.config.attemptToLogAssertCaller) { var callerNameMatch = bAssert.caller.toString().match(/function ([^(]+)/); if (callerNameMatch && callerNameMatch[1]) { console.error('<chai>' + err + '<caller>' + callerNameMatch[1] + '</caller></chai>'); } else console.error('<chai>' + err + '<callerunknown /></chai>'); //console.log('caller was '+ callerNameMatch[1]); } else { console.error('<chai>' + err + '</chai>'); } } } //end catch if (success === true && onSuccess) { onSuccess(); } };
  • 17.
  • 18. My Chai (not Mai-Tai) bAssert(function(){ assert.typeOf('test','string','test is a string');}); bAssert(function(){ var currentItemIndex=page.evaluate(function(){ return $('.first-index:first').text(); }); console.log('currentItemIndex='+currentItemIndex); assert.notEqual(currentItemIndex,'','current item index should never be empty'); });
  • 20. Topics Available ● Meta-Programming ○ T4 ○ CoffeeScript ● Javascript Topics ○ Knockout ■ Custom bindings ■ KoGrid ■ jQuery ● ALM ○ TFS - Custom Workflow builds ○ SonarSource Code quality analysis ● Functional Programming
  • 21. More topics ● Unit testing ● Entity Framework ● Dependency Injection ● Asp.Net MVC4 ● MvcOData ○ Knockout -> OdataUrl Generation -> Ajax -> MVC -> WCF Data services -> Entity Framework