SlideShare a Scribd company logo
Automated Javascript Unit Testing Ryan Chambers [email_address] Intelliware Development
Outline Why should I write javascript tests? Testing goals The code we’re going to test How can I automate the tests? JS Test Driver QUnit and Selenium Jasmine Maven Plugin QUnit, PhantomJS and JS Test Runner
Testing Goals Easy to develop tests in eclipse Tests runnable as part of maven build Fast Cross-browser
Why write javascript unit tests? Why write java tests? Faster to test unit tests than to browse actual application Can help find new bugs Easy to add to part of build process, giving you another layer of testing
Code to be tested var  validation =  function () { … return { validateAlphaNumeric:  function (field) {..}, validateUsername :  function  (field) { $.ajax({…}); } } }
JS Test Driver Project from google to automate javascript testing Provides a javascript unit testing framework Maven plug-in and eclipse plug-in Uses real browsers However, I had problems with Chrome Browsers weren’t always closed after No need to create fixture html – but you can specify html in each test Server isn’t needed unless for AJAX Has a QUnit adapter Some flakiness, nothing I could reproduce reliably but I felt like it did weird stuff sometimes http:// code.google.com/p/js -test-driver/
Test Code TestCase(&quot;validateAlphaNumeric&quot;, { &quot;test validateAlphaNumeric valid&quot; : function() { /*:DOC input = <input type=&quot;text&quot; id=&quot;test_field&quot; value=&quot;aB1&quot; /> */ var field = $(this.input), isValid; isValid = validation.validateAlphaNumeric(field); assertEquals(&quot;aB1 should be valid&quot;, true, isValid); }, &quot;test validateAlphaNumeric invalid&quot; : function() { /*:DOC input = <input type=&quot;text&quot; id=&quot;test_field&quot; value=&quot;!&quot; /> */ var field = $(this.input), isValid; isValid = validation.validateAlphaNumeric(field); assertEquals(&quot;! is not valid alphanumeric value&quot;, false, isValid); } });
Sinon.JS A library for standalone test spies, stubs and mocks Can also fake XHR (AJAX) and servers http:// sinonjs.org /
Testing AJAX with SinonJS TestCase(&quot;validateUsername&quot;, sinon.testCase({ setUp : function() { validation.reset(); this.server = sinon.fakeServerWithClock.create(); /*:DOC input = <input type=&quot;text&quot; id=&quot;test_field&quot; value=&quot;!&quot; /> */ }, tearDown: function() { this.server.restore(); }, &quot;test validateUsername user name already used&quot; : function() { var field = $(this.input), isValid; this.server.respondWith(createFakeResponse('error : username already used')); isValid = callValidation(field, this.server); assertEquals(&quot;should have got username already used error&quot;, isValid, false); } }
Testing AJAX with SinonJS function createFakeResponse(responseCode) { return [ 200, { &quot;Content-Type&quot;: &quot;text/xml&quot; }, '<?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>  <result>' + responseCode +  '</result>' ]; } function callValidation(field, server) { validation.validateUsername(field); server.respond(); return validation.validateAlphaNumeric(field); }
JS Test Runner Demo Demo of eclipse plug-in Demo of maven build https://github.com/ryan-chambers/jstestdriver-sample-project
QUnit and Selenium QUnit is a javascript testing library originally written to test jQuery Selenium tests using real browsers very slow Typically only one browser is tested Meant for automated testing of page flows, not javascript unit testing I wrote a sample test that only records whether all tests pass or not could possibly be updated to record actual error Requires creating an html page to host tests https:// github.com/jquery/qunit
QUnit Test page Includes all required css and javascript Adds elements to DOM that are required for test <input type= &quot;text&quot;  id= &quot;test_field&quot;  value= &quot;!&quot;  />
QUnit Tests - setup module(&quot;validation&quot;, { setup :  function () { this.field = $('#test_field');   validation.reset(); }, tearDown:  function  () { this .xhr.restore(); } });
QUnit Tests test(&quot;validateAlphaNumeric invalid&quot;,  function () { this.field.val('!'); var  isValid =  validation.validateAlphaNumeric( this.field); equal(isValid,  false , &quot;! Should not be a valid alphanumeric value&quot;); });
QUnit Tests with SinonJS function  testFakeUserValidationWithResponse(responseCode, testHandler) { var  server = sinon.fakeServerWithClock.create(); try  { server.respondWith([ 200, { &quot;Content-Type&quot;: &quot;text/xml&quot; }, '<?xml version=&quot;1.0&quot; encoding=&quot;UTF- 8&quot;?><result>‘ + responseCode + '</ result >'   ]);   testHandler(server); }  finally  { server.restore(); } }
QUnit tests with SinonJS test(&quot;validateUsername user name already used&quot;,  function ( { var that = this; testFakeUserValidationWithResponse(username_ already_used',  function (server) { validation.validateUsername(that.field); server.respond(); var  isUsernameValid = validation.isUsernameValid(); equal(isUsernameValid,  false , &quot;should have got   username already used error&quot;); }); });
Selenium public   class  ValidationIntegrationTest { private  WebDriver driver; @Before public   void  setUp()  throws  Exception { driver =  new  FirefoxDriver(); } @Test public   void  testFormsIntegration()  throws  Exception { driver.get(&quot;http://localhost:8080/validation.html&quot;); assertPageIsLoaded(); List<WebElement> failedElements = driver.findElements(By. xpath (&quot;//span[@class='fail']&quot;)); // could do more here to return failure messages Assert. assertEquals (0, failedElements.size()); } private   void  assertPageIsLoaded() { driver.findElement(By. id (&quot;qunit-header&quot;)); } @After public   void  tearDown()  throws  Exception { driver.close(); } }
QUnit demo View page in browser Run unit test in eclipse w/ Jetty https://github.com/ryan-chambers/qunit-selenium-sample-project
Jasmine Maven Plug-in Jasmine is a BDD javascript unit test framework You create a “spec” in a DSL that almost looks like English BDD is very popular in Ruby on Rails https://github.com/pivotal/jasmine/wiki Jasmine maven plug-in looks in certain directories for tests and their specs Can configure includes for libraries (eg. Jasmine/sinon plug-in) Uses HTMLUnit for DOM https://github.com/searls/jasmine-maven-plugin
Jasmine Specs describe('validation',  function () { it('should detect valid alphanumeric sequences',  function () { var  isValidAlphaNumeric =  validation.isAlphaNumeric('aA1'); expect(isValidAlphaNumeric).toEqual( true ); }); it('should detect invalid alphanumeric sequences',  function () { var  isValidAlphaNumeric =  validation.isAlphaNumeric('ab@google.com'); expect(isValidAlphaNumeric).toEqual( false ); }); });
Jasmine Maven Plug-in demo Run tests in browser mvn jasmine:bdd http://localhost:8234  Run maven build https:// github.com/ryan -chambers/maven-jasmine-sample-project
QUnit, PhantomJS and JS Test Runner PhantomJS is a command-line tool that embeds WebKit and can run javascript Very fast, since there is no browser http:// www.phantomjs.org / JS Test Runner is a JUnit test runner that uses QUnit and Phantomjs for javascript Runnable from maven and eclipse http://js-testrunner.codehaus.org /
JS Test Runner @RunWith(JSTestSuiteRunner. class ) @JSTestSuiteRunner.Include(value=&quot;validation.html&quot;) public   class  ValidationJSTest { }
QUnit, PhantomJS and JS Test Runner Run unit tests from Eclipse Run build from maven https://github.com/ryan-chambers/jstest-runner-sample-project
Questions?
Ad

Recommended

Automated Frontend Testing
Automated Frontend Testing
Neil Crosby
 
Nightwatch at Tilt
Nightwatch at Tilt
Dave King
 
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...
Iakiv Kramarenko
 
Join the darkside: Selenium testing with Nightwatch.js
Join the darkside: Selenium testing with Nightwatch.js
Seth McLaughlin
 
Compatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensions
Kai Cui
 
20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing
Vladimir Roudakov
 
Easy tests with Selenide and Easyb
Easy tests with Selenide and Easyb
Iakiv Kramarenko
 
Polyglot automation - QA Fest - 2015
Polyglot automation - QA Fest - 2015
Iakiv Kramarenko
 
Night Watch with QA
Night Watch with QA
Carsten Sandtner
 
Testing in JavaScript - August 2018 - WebElement Bardejov
Testing in JavaScript - August 2018 - WebElement Bardejov
Marian Rusnak
 
081107 Sammy Eclipse Summit2
081107 Sammy Eclipse Summit2
mkempka
 
Clean tests good tests
Clean tests good tests
Shopsys Framework
 
Metaprogramming 101
Metaprogramming 101
Nando Vieira
 
Apex 5 plugins for everyone version 2018
Apex 5 plugins for everyone version 2018
Alan Arentsen
 
Testing React Applications
Testing React Applications
stbaechler
 
Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]
Iakiv Kramarenko
 
BDD with Behat and Symfony2
BDD with Behat and Symfony2
katalisha
 
Write Selenide in Python 15 min
Write Selenide in Python 15 min
Iakiv Kramarenko
 
Migration testing framework
Migration testing framework
IndicThreads
 
Selenium
Selenium
g2ix
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
Jim Lynch
 
Testing in AngularJS
Testing in AngularJS
Peter Drinnan
 
Easy automation.py
Easy automation.py
Iakiv Kramarenko
 
Browser Automated Testing Frameworks - Nightwatch.js
Browser Automated Testing Frameworks - Nightwatch.js
Luís Bastião Silva
 
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
Wim Selles
 
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
Iakiv Kramarenko
 
Codeception presentation
Codeception presentation
Andrei Burian
 
Test like a pro with Ember.js
Test like a pro with Ember.js
Mike North
 
Why Nortel Went Bankrupt
Why Nortel Went Bankrupt
Chris Sandström
 
Canadian Healthcare Codes and Terminology Standards
Canadian Healthcare Codes and Terminology Standards
Intelliware Development Inc.
 

More Related Content

What's hot (20)

Night Watch with QA
Night Watch with QA
Carsten Sandtner
 
Testing in JavaScript - August 2018 - WebElement Bardejov
Testing in JavaScript - August 2018 - WebElement Bardejov
Marian Rusnak
 
081107 Sammy Eclipse Summit2
081107 Sammy Eclipse Summit2
mkempka
 
Clean tests good tests
Clean tests good tests
Shopsys Framework
 
Metaprogramming 101
Metaprogramming 101
Nando Vieira
 
Apex 5 plugins for everyone version 2018
Apex 5 plugins for everyone version 2018
Alan Arentsen
 
Testing React Applications
Testing React Applications
stbaechler
 
Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]
Iakiv Kramarenko
 
BDD with Behat and Symfony2
BDD with Behat and Symfony2
katalisha
 
Write Selenide in Python 15 min
Write Selenide in Python 15 min
Iakiv Kramarenko
 
Migration testing framework
Migration testing framework
IndicThreads
 
Selenium
Selenium
g2ix
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
Jim Lynch
 
Testing in AngularJS
Testing in AngularJS
Peter Drinnan
 
Easy automation.py
Easy automation.py
Iakiv Kramarenko
 
Browser Automated Testing Frameworks - Nightwatch.js
Browser Automated Testing Frameworks - Nightwatch.js
Luís Bastião Silva
 
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
Wim Selles
 
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
Iakiv Kramarenko
 
Codeception presentation
Codeception presentation
Andrei Burian
 
Test like a pro with Ember.js
Test like a pro with Ember.js
Mike North
 
Testing in JavaScript - August 2018 - WebElement Bardejov
Testing in JavaScript - August 2018 - WebElement Bardejov
Marian Rusnak
 
081107 Sammy Eclipse Summit2
081107 Sammy Eclipse Summit2
mkempka
 
Metaprogramming 101
Metaprogramming 101
Nando Vieira
 
Apex 5 plugins for everyone version 2018
Apex 5 plugins for everyone version 2018
Alan Arentsen
 
Testing React Applications
Testing React Applications
stbaechler
 
Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]
Iakiv Kramarenko
 
BDD with Behat and Symfony2
BDD with Behat and Symfony2
katalisha
 
Write Selenide in Python 15 min
Write Selenide in Python 15 min
Iakiv Kramarenko
 
Migration testing framework
Migration testing framework
IndicThreads
 
Selenium
Selenium
g2ix
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
Jim Lynch
 
Testing in AngularJS
Testing in AngularJS
Peter Drinnan
 
Browser Automated Testing Frameworks - Nightwatch.js
Browser Automated Testing Frameworks - Nightwatch.js
Luís Bastião Silva
 
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
Wim Selles
 
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
Iakiv Kramarenko
 
Codeception presentation
Codeception presentation
Andrei Burian
 
Test like a pro with Ember.js
Test like a pro with Ember.js
Mike North
 

Viewers also liked (20)

Why Nortel Went Bankrupt
Why Nortel Went Bankrupt
Chris Sandström
 
Canadian Healthcare Codes and Terminology Standards
Canadian Healthcare Codes and Terminology Standards
Intelliware Development Inc.
 
I2 Argentina Unitech
I2 Argentina Unitech
UNITECH S.A.
 
Hong kong
Hong kong
Sonya Fay McKenzie
 
Environmental Law for Road Builders
Environmental Law for Road Builders
DSaxe
 
City of deception
City of deception
Dr Saim Ali soomro
 
Quelle gouvernance pour le numérique?
Quelle gouvernance pour le numérique?
Antoine Vigneron
 
Clinical development, contract & outsourcing in mena & asia pac webinar-l aju...
Clinical development, contract & outsourcing in mena & asia pac webinar-l aju...
Larry Ajuwon
 
Enterprise Wearables: Wearing Our Parts On Our Sleeves - How Wearable Technol...
Enterprise Wearables: Wearing Our Parts On Our Sleeves - How Wearable Technol...
Intelliware Development Inc.
 
Add 2009 10
Add 2009 10
RUAULT
 
Coding is the new literacy to make a difference in the world
Coding is the new literacy to make a difference in the world
mcd_boulanger
 
Refactoring legacy code driven by tests - ITA
Refactoring legacy code driven by tests - ITA
Luca Minudel
 
Proyecto de Protección Ambiental de Bosawas, NIcaragua
Proyecto de Protección Ambiental de Bosawas, NIcaragua
ONGAWA, Ingeniería para el Desarrollo Humano
 
Xerox Corporation Fraud Case
Xerox Corporation Fraud Case
Augustin Bangalore
 
5 mythes de la marche au ralenti
5 mythes de la marche au ralenti
ellipsos inc.
 
U.S. Economic Sanctions Update
U.S. Economic Sanctions Update
Jon Yormick
 
Agile Story Writing
Agile Story Writing
Intelliware Development Inc.
 
Agile Release & Iteration Planning
Agile Release & Iteration Planning
Intelliware Development Inc.
 
Bioterrorism
Bioterrorism
ReportLinker.com
 
Lawsuit filed against battery startup Envia by former Envia employees
Lawsuit filed against battery startup Envia by former Envia employees
katiefehren
 
Canadian Healthcare Codes and Terminology Standards
Canadian Healthcare Codes and Terminology Standards
Intelliware Development Inc.
 
I2 Argentina Unitech
I2 Argentina Unitech
UNITECH S.A.
 
Environmental Law for Road Builders
Environmental Law for Road Builders
DSaxe
 
Quelle gouvernance pour le numérique?
Quelle gouvernance pour le numérique?
Antoine Vigneron
 
Clinical development, contract & outsourcing in mena & asia pac webinar-l aju...
Clinical development, contract & outsourcing in mena & asia pac webinar-l aju...
Larry Ajuwon
 
Enterprise Wearables: Wearing Our Parts On Our Sleeves - How Wearable Technol...
Enterprise Wearables: Wearing Our Parts On Our Sleeves - How Wearable Technol...
Intelliware Development Inc.
 
Add 2009 10
Add 2009 10
RUAULT
 
Coding is the new literacy to make a difference in the world
Coding is the new literacy to make a difference in the world
mcd_boulanger
 
Refactoring legacy code driven by tests - ITA
Refactoring legacy code driven by tests - ITA
Luca Minudel
 
5 mythes de la marche au ralenti
5 mythes de la marche au ralenti
ellipsos inc.
 
U.S. Economic Sanctions Update
U.S. Economic Sanctions Update
Jon Yormick
 
Lawsuit filed against battery startup Envia by former Envia employees
Lawsuit filed against battery startup Envia by former Envia employees
katiefehren
 
Ad

Similar to Automated javascript unit testing (20)

Test strategy for web development
Test strategy for web development
alice yang
 
Automated Testing Of Web Applications Using XML
Automated Testing Of Web Applications Using XML
diongillard
 
Test-Driven JavaScript Development (JavaZone 2010)
Test-Driven JavaScript Development (JavaZone 2010)
Christian Johansen
 
Java script unit testing
Java script unit testing
Mats Bryntse
 
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Alex Chaffee
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
jeresig
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
Mats Bryntse
 
On fx jsj unit - an idea to test javascript codes with junit and javafx
On fx jsj unit - an idea to test javascript codes with junit and javafx
Shinya Mochida
 
How do I write Testable Javascript
How do I write Testable Javascript
ColdFusionConference
 
How do I write testable javascript?
How do I write testable javascript?
devObjective
 
How do I write Testable Javascript?
How do I write Testable Javascript?
Gavin Pickin
 
Acceptance Testing With Selenium
Acceptance Testing With Selenium
elliando dias
 
Understanding JavaScript Testing
Understanding JavaScript Testing
jeresig
 
JavaScript Unit Testing
JavaScript Unit Testing
Christian Johansen
 
Unit Testing JavaScript Applications
Unit Testing JavaScript Applications
Ynon Perek
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API
Gavin Pickin
 
3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API -
Ortus Solutions, Corp
 
How to write Testable Javascript
How to write Testable Javascript
ColdFusionConference
 
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
Gavin Pickin
 
Test strategy for web development
Test strategy for web development
alice yang
 
Automated Testing Of Web Applications Using XML
Automated Testing Of Web Applications Using XML
diongillard
 
Test-Driven JavaScript Development (JavaZone 2010)
Test-Driven JavaScript Development (JavaZone 2010)
Christian Johansen
 
Java script unit testing
Java script unit testing
Mats Bryntse
 
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Alex Chaffee
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
jeresig
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
Mats Bryntse
 
On fx jsj unit - an idea to test javascript codes with junit and javafx
On fx jsj unit - an idea to test javascript codes with junit and javafx
Shinya Mochida
 
How do I write Testable Javascript
How do I write Testable Javascript
ColdFusionConference
 
How do I write testable javascript?
How do I write testable javascript?
devObjective
 
How do I write Testable Javascript?
How do I write Testable Javascript?
Gavin Pickin
 
Acceptance Testing With Selenium
Acceptance Testing With Selenium
elliando dias
 
Understanding JavaScript Testing
Understanding JavaScript Testing
jeresig
 
Unit Testing JavaScript Applications
Unit Testing JavaScript Applications
Ynon Perek
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API
Gavin Pickin
 
3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API -
Ortus Solutions, Corp
 
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
Gavin Pickin
 
Ad

Recently uploaded (20)

PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 

Automated javascript unit testing

  • 1. Automated Javascript Unit Testing Ryan Chambers [email_address] Intelliware Development
  • 2. Outline Why should I write javascript tests? Testing goals The code we’re going to test How can I automate the tests? JS Test Driver QUnit and Selenium Jasmine Maven Plugin QUnit, PhantomJS and JS Test Runner
  • 3. Testing Goals Easy to develop tests in eclipse Tests runnable as part of maven build Fast Cross-browser
  • 4. Why write javascript unit tests? Why write java tests? Faster to test unit tests than to browse actual application Can help find new bugs Easy to add to part of build process, giving you another layer of testing
  • 5. Code to be tested var validation = function () { … return { validateAlphaNumeric: function (field) {..}, validateUsername : function (field) { $.ajax({…}); } } }
  • 6. JS Test Driver Project from google to automate javascript testing Provides a javascript unit testing framework Maven plug-in and eclipse plug-in Uses real browsers However, I had problems with Chrome Browsers weren’t always closed after No need to create fixture html – but you can specify html in each test Server isn’t needed unless for AJAX Has a QUnit adapter Some flakiness, nothing I could reproduce reliably but I felt like it did weird stuff sometimes http:// code.google.com/p/js -test-driver/
  • 7. Test Code TestCase(&quot;validateAlphaNumeric&quot;, { &quot;test validateAlphaNumeric valid&quot; : function() { /*:DOC input = <input type=&quot;text&quot; id=&quot;test_field&quot; value=&quot;aB1&quot; /> */ var field = $(this.input), isValid; isValid = validation.validateAlphaNumeric(field); assertEquals(&quot;aB1 should be valid&quot;, true, isValid); }, &quot;test validateAlphaNumeric invalid&quot; : function() { /*:DOC input = <input type=&quot;text&quot; id=&quot;test_field&quot; value=&quot;!&quot; /> */ var field = $(this.input), isValid; isValid = validation.validateAlphaNumeric(field); assertEquals(&quot;! is not valid alphanumeric value&quot;, false, isValid); } });
  • 8. Sinon.JS A library for standalone test spies, stubs and mocks Can also fake XHR (AJAX) and servers http:// sinonjs.org /
  • 9. Testing AJAX with SinonJS TestCase(&quot;validateUsername&quot;, sinon.testCase({ setUp : function() { validation.reset(); this.server = sinon.fakeServerWithClock.create(); /*:DOC input = <input type=&quot;text&quot; id=&quot;test_field&quot; value=&quot;!&quot; /> */ }, tearDown: function() { this.server.restore(); }, &quot;test validateUsername user name already used&quot; : function() { var field = $(this.input), isValid; this.server.respondWith(createFakeResponse('error : username already used')); isValid = callValidation(field, this.server); assertEquals(&quot;should have got username already used error&quot;, isValid, false); } }
  • 10. Testing AJAX with SinonJS function createFakeResponse(responseCode) { return [ 200, { &quot;Content-Type&quot;: &quot;text/xml&quot; }, '<?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <result>' + responseCode + '</result>' ]; } function callValidation(field, server) { validation.validateUsername(field); server.respond(); return validation.validateAlphaNumeric(field); }
  • 11. JS Test Runner Demo Demo of eclipse plug-in Demo of maven build https://github.com/ryan-chambers/jstestdriver-sample-project
  • 12. QUnit and Selenium QUnit is a javascript testing library originally written to test jQuery Selenium tests using real browsers very slow Typically only one browser is tested Meant for automated testing of page flows, not javascript unit testing I wrote a sample test that only records whether all tests pass or not could possibly be updated to record actual error Requires creating an html page to host tests https:// github.com/jquery/qunit
  • 13. QUnit Test page Includes all required css and javascript Adds elements to DOM that are required for test <input type= &quot;text&quot; id= &quot;test_field&quot; value= &quot;!&quot; />
  • 14. QUnit Tests - setup module(&quot;validation&quot;, { setup : function () { this.field = $('#test_field'); validation.reset(); }, tearDown: function () { this .xhr.restore(); } });
  • 15. QUnit Tests test(&quot;validateAlphaNumeric invalid&quot;, function () { this.field.val('!'); var isValid = validation.validateAlphaNumeric( this.field); equal(isValid, false , &quot;! Should not be a valid alphanumeric value&quot;); });
  • 16. QUnit Tests with SinonJS function testFakeUserValidationWithResponse(responseCode, testHandler) { var server = sinon.fakeServerWithClock.create(); try { server.respondWith([ 200, { &quot;Content-Type&quot;: &quot;text/xml&quot; }, '<?xml version=&quot;1.0&quot; encoding=&quot;UTF- 8&quot;?><result>‘ + responseCode + '</ result >' ]); testHandler(server); } finally { server.restore(); } }
  • 17. QUnit tests with SinonJS test(&quot;validateUsername user name already used&quot;, function ( { var that = this; testFakeUserValidationWithResponse(username_ already_used', function (server) { validation.validateUsername(that.field); server.respond(); var isUsernameValid = validation.isUsernameValid(); equal(isUsernameValid, false , &quot;should have got username already used error&quot;); }); });
  • 18. Selenium public class ValidationIntegrationTest { private WebDriver driver; @Before public void setUp() throws Exception { driver = new FirefoxDriver(); } @Test public void testFormsIntegration() throws Exception { driver.get(&quot;http://localhost:8080/validation.html&quot;); assertPageIsLoaded(); List<WebElement> failedElements = driver.findElements(By. xpath (&quot;//span[@class='fail']&quot;)); // could do more here to return failure messages Assert. assertEquals (0, failedElements.size()); } private void assertPageIsLoaded() { driver.findElement(By. id (&quot;qunit-header&quot;)); } @After public void tearDown() throws Exception { driver.close(); } }
  • 19. QUnit demo View page in browser Run unit test in eclipse w/ Jetty https://github.com/ryan-chambers/qunit-selenium-sample-project
  • 20. Jasmine Maven Plug-in Jasmine is a BDD javascript unit test framework You create a “spec” in a DSL that almost looks like English BDD is very popular in Ruby on Rails https://github.com/pivotal/jasmine/wiki Jasmine maven plug-in looks in certain directories for tests and their specs Can configure includes for libraries (eg. Jasmine/sinon plug-in) Uses HTMLUnit for DOM https://github.com/searls/jasmine-maven-plugin
  • 21. Jasmine Specs describe('validation', function () { it('should detect valid alphanumeric sequences', function () { var isValidAlphaNumeric = validation.isAlphaNumeric('aA1'); expect(isValidAlphaNumeric).toEqual( true ); }); it('should detect invalid alphanumeric sequences', function () { var isValidAlphaNumeric = validation.isAlphaNumeric('[email protected]'); expect(isValidAlphaNumeric).toEqual( false ); }); });
  • 22. Jasmine Maven Plug-in demo Run tests in browser mvn jasmine:bdd http://localhost:8234 Run maven build https:// github.com/ryan -chambers/maven-jasmine-sample-project
  • 23. QUnit, PhantomJS and JS Test Runner PhantomJS is a command-line tool that embeds WebKit and can run javascript Very fast, since there is no browser http:// www.phantomjs.org / JS Test Runner is a JUnit test runner that uses QUnit and Phantomjs for javascript Runnable from maven and eclipse http://js-testrunner.codehaus.org /
  • 24. JS Test Runner @RunWith(JSTestSuiteRunner. class ) @JSTestSuiteRunner.Include(value=&quot;validation.html&quot;) public class ValidationJSTest { }
  • 25. QUnit, PhantomJS and JS Test Runner Run unit tests from Eclipse Run build from maven https://github.com/ryan-chambers/jstest-runner-sample-project