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?

More Related Content

ZIP
Automated Frontend Testing
PDF
Nightwatch at Tilt
PDF
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...
PDF
Join the darkside: Selenium testing with Nightwatch.js
PPTX
Compatibility Detector Tool of Chrome extensions
PDF
20160905 - BrisJS - nightwatch testing
PDF
Easy tests with Selenide and Easyb
PDF
Polyglot automation - QA Fest - 2015
Automated Frontend Testing
Nightwatch at Tilt
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...
Join the darkside: Selenium testing with Nightwatch.js
Compatibility Detector Tool of Chrome extensions
20160905 - BrisJS - nightwatch testing
Easy tests with Selenide and Easyb
Polyglot automation - QA Fest - 2015

What's hot (20)

PDF
Night Watch with QA
PDF
Testing in JavaScript - August 2018 - WebElement Bardejov
PDF
081107 Sammy Eclipse Summit2
PPTX
Clean tests good tests
PDF
Metaprogramming 101
PDF
Apex 5 plugins for everyone version 2018
PPTX
Testing React Applications
PDF
Kiss PageObjects [01-2017]
KEY
BDD with Behat and Symfony2
PPTX
Write Selenide in Python 15 min
PPT
Migration testing framework
PDF
Selenium
PDF
Intro to Unit Testing in AngularJS
PPT
Testing in AngularJS
PDF
Easy automation.py
PPTX
Browser Automated Testing Frameworks - Nightwatch.js
PDF
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
PDF
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
PDF
Codeception presentation
PPTX
Test like a pro with Ember.js
Night Watch with QA
Testing in JavaScript - August 2018 - WebElement Bardejov
081107 Sammy Eclipse Summit2
Clean tests good tests
Metaprogramming 101
Apex 5 plugins for everyone version 2018
Testing React Applications
Kiss PageObjects [01-2017]
BDD with Behat and Symfony2
Write Selenide in Python 15 min
Migration testing framework
Selenium
Intro to Unit Testing in AngularJS
Testing in AngularJS
Easy automation.py
Browser Automated Testing Frameworks - Nightwatch.js
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
Codeception presentation
Test like a pro with Ember.js
Ad

Viewers also liked (20)

PDF
Why Nortel Went Bankrupt
PPT
Canadian Healthcare Codes and Terminology Standards
PDF
I2 Argentina Unitech
DOC
PDF
Environmental Law for Road Builders
DOCX
City of deception
PDF
Quelle gouvernance pour le numérique?
PDF
Clinical development, contract & outsourcing in mena & asia pac webinar-l aju...
PDF
Enterprise Wearables: Wearing Our Parts On Our Sleeves - How Wearable Technol...
ODP
Add 2009 10
PDF
Coding is the new literacy to make a difference in the world
PPTX
Refactoring legacy code driven by tests - ITA
PPT
Proyecto de Protección Ambiental de Bosawas, NIcaragua
DOC
Xerox Corporation Fraud Case
KEY
5 mythes de la marche au ralenti
PPTX
U.S. Economic Sanctions Update
PPTX
Agile Story Writing
PPTX
Agile Release & Iteration Planning
PDF
Bioterrorism
PDF
Lawsuit filed against battery startup Envia by former Envia employees
Why Nortel Went Bankrupt
Canadian Healthcare Codes and Terminology Standards
I2 Argentina Unitech
Environmental Law for Road Builders
City of deception
Quelle gouvernance pour le numérique?
Clinical development, contract & outsourcing in mena & asia pac webinar-l aju...
Enterprise Wearables: Wearing Our Parts On Our Sleeves - How Wearable Technol...
Add 2009 10
Coding is the new literacy to make a difference in the world
Refactoring legacy code driven by tests - ITA
Proyecto de Protección Ambiental de Bosawas, NIcaragua
Xerox Corporation Fraud Case
5 mythes de la marche au ralenti
U.S. Economic Sanctions Update
Agile Story Writing
Agile Release & Iteration Planning
Bioterrorism
Lawsuit filed against battery startup Envia by former Envia employees
Ad

Similar to Automated javascript unit testing (20)

PPT
Test strategy for web development
PDF
Automated acceptance test
PPTX
Jasmine with JS-Test-Driver
PPTX
Testing JavaScript with Jasmine in Rails Applications
ODP
Unit Testing and Coverage for AngularJS
PDF
Adventures In JavaScript Testing
PPTX
Introduction to AJAX and DWR
PDF
Writing testable js [by Ted Piotrowski]
ODP
Scti 2011 minicurso jquery
PDF
Javascript Unit Testing
PPT
Pragmatic Parallels: Java and JavaScript
PPT
JavaScript Unit Testing
ODP
Bring the fun back to java
PDF
Testing AngularJS
PPTX
A few good JavaScript development tools
PPTX
Slaven tomac unit testing in angular js
PPT
Gems Of Selenium
PDF
Ember testing internals with ember cli
PPTX
Selenium scripts help full for student .pptx
PDF
Javascript testing: tools of the trade
Test strategy for web development
Automated acceptance test
Jasmine with JS-Test-Driver
Testing JavaScript with Jasmine in Rails Applications
Unit Testing and Coverage for AngularJS
Adventures In JavaScript Testing
Introduction to AJAX and DWR
Writing testable js [by Ted Piotrowski]
Scti 2011 minicurso jquery
Javascript Unit Testing
Pragmatic Parallels: Java and JavaScript
JavaScript Unit Testing
Bring the fun back to java
Testing AngularJS
A few good JavaScript development tools
Slaven tomac unit testing in angular js
Gems Of Selenium
Ember testing internals with ember cli
Selenium scripts help full for student .pptx
Javascript testing: tools of the trade

Recently uploaded (20)

PPT
Geologic Time for studying geology for geologist
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PDF
A review of recent deep learning applications in wood surface defect identifi...
PPTX
Modernising the Digital Integration Hub
PPTX
Chapter 5: Probability Theory and Statistics
PDF
How IoT Sensor Integration in 2025 is Transforming Industries Worldwide
PDF
The influence of sentiment analysis in enhancing early warning system model f...
PDF
Zenith AI: Advanced Artificial Intelligence
PPTX
GROUP4NURSINGINFORMATICSREPORT-2 PRESENTATION
PDF
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
PDF
A proposed approach for plagiarism detection in Myanmar Unicode text
PDF
sbt 2.0: go big (Scala Days 2025 edition)
DOCX
search engine optimization ppt fir known well about this
PPTX
AI IN MARKETING- PRESENTED BY ANWAR KABIR 1st June 2025.pptx
PDF
Improvisation in detection of pomegranate leaf disease using transfer learni...
PPT
Module 1.ppt Iot fundamentals and Architecture
PDF
Consumable AI The What, Why & How for Small Teams.pdf
Geologic Time for studying geology for geologist
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
sustainability-14-14877-v2.pddhzftheheeeee
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
A contest of sentiment analysis: k-nearest neighbor versus neural network
A review of recent deep learning applications in wood surface defect identifi...
Modernising the Digital Integration Hub
Chapter 5: Probability Theory and Statistics
How IoT Sensor Integration in 2025 is Transforming Industries Worldwide
The influence of sentiment analysis in enhancing early warning system model f...
Zenith AI: Advanced Artificial Intelligence
GROUP4NURSINGINFORMATICSREPORT-2 PRESENTATION
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
A proposed approach for plagiarism detection in Myanmar Unicode text
sbt 2.0: go big (Scala Days 2025 edition)
search engine optimization ppt fir known well about this
AI IN MARKETING- PRESENTED BY ANWAR KABIR 1st June 2025.pptx
Improvisation in detection of pomegranate leaf disease using transfer learni...
Module 1.ppt Iot fundamentals and Architecture
Consumable AI The What, Why & How for Small Teams.pdf

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