SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Scripting GeoServer with GeoScript
Scripting GeoServer with GeoScriptScripting GeoServer with GeoScript
Scripting GeoServer with GeoScript
Justin Deoliveira
 
Zero to Testing in JavaScript
Zero to Testing in JavaScriptZero to Testing in JavaScript
Zero to Testing in JavaScript
pamselle
 

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

Destaque

Василевский Илья (Fun-box): "автоматизация браузера при помощи PhantomJS"
Василевский Илья (Fun-box): "автоматизация браузера при помощи PhantomJS"Василевский Илья (Fun-box): "автоматизация браузера при помощи PhantomJS"
Василевский Илья (Fun-box): "автоматизация браузера при помощи PhantomJS"
Provectus
 
Phantom js quick start
Phantom js quick startPhantom js quick start
Phantom js quick start
ji guang
 

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

Semelhante a Js testing

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

Mais 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
 

Último

Último (20)

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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

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