SlideShare a Scribd company logo
Testing JavaScript
with Jasmine
Carolyn Cole
cam156@psu.edu
Hector Correa
hjc14@psu.edu
The Pennsylvania State University
The Problem
Testing JavaScript with Ruby tools is hard
‱ Feature Tests
‱ tend to be slow
‱ hard to test error cases
‱ View Tests
‱ do not test JavaScript
Quick Demo
https://github.com/hectorcorrea/riceonrails
The Solution
‱ Integrate a JavaScript Testing
Framework
‱ There are many options
‱ Karma, QUnit, Buster, Mocha.js, Jasmine, 

‱ http://stackoverflow.com/questions/300855/javascri
pt-unit-test-tools-for-tdd
Why Jasmine?
‱ Easily integrated with existing tests
‱ Familiar syntax to RSpec
‱ Built in matchers
‱ Mock objects
‱ Control time
Familiar Syntax - JavaScript
JavaScript/Jasmine
describe(”something", function() {
beforeEach(function() {
...
});
it(”does something", function() {
...
});
});
Ruby/Rspec
describe ”something" do
before do
...
end
it "does something" do
...
end
end
Familiar Syntax - CoffeeScript
CoffeeScript/Jasmine
describe ”something", ->
beforeEach ->
...
it "does something", ->
...
Ruby/Rspec
describe ”something" do
before do
...
end
it "does something" do
...
end
end
Running Jasmine
‱ User Interface
$ rake jasmine
> go to localhost:8888 to view results
‱ Continuous Integration
$ rake jasmine:ci
Waiting for jasmine server on 58458...
jasmine server started
..
2 specs, 0 failures
[2015-09-21 10:15:15] INFO going to shutdown ...
[2015-09-21 10:15:15] INFO WEBrick::HTTPServer#start done
Testing plain vanilla JavaScript
// Calculator.js
Calculator.addNumbers = function(a, b) {
return a + b;
}
// CalculatorSpec.js
describe("Calculator", function() {
it("adds two numbers", function() {
result = Calculator.addNumbers(4,5);
expect(result).toEqual(9);
});
});
Testing DOM elements (1/2)
// Calculator.js
Calculator.updateUI = function() {
var a = $("#number1").val();
var b = $("#number2").val();
var result = Calculator.addNumbers(a, b);
$("#resultGoesHere").text(result);
}
Testing DOM elements (2/2)
// CalculatorUISpec.js
describe("Calculator UI", function() {
it("updates the UI with the result", function() {
var html = '<input id="number1" value="4"/> ' +
'<input id="number2" value="3"/> ' +
'<span id="resultGoesHere"/>';
setFixtures(html);
Calculator.updateUI();
var result = $("#resultGoesHere");
expect(result.text()).toEqual("7");
});
});
Expect and matchers
‱ Syntax similar to Rspec
expect(result.text()).toEqual("7");
var button = $("#theButton");
expect(button).toBeDisabled();
Matchers
‱ Built-in
‱ toMatch, not.toMatch, toBeDefined,
not.toBeDefined, toBeNull, toBeTruthy,
toContain, toEqual, ...
‱ http://jasmine.github.io/2.0/introduction.html
‱ Third party matchers (e.g. Jasmine jQuery)
‱ $(“#someID”)
‱ toBeDisabled, not.toBeDisabled, ...
‱ https://github.com/velesin/jasmine-jquery
‱ Write your own
Mock Objects - Spies
‱ Spies can be used for any
JavaScript function
‱ All calls and arguments to a spy are
tracked
‱ It only exists in the block and will be
removed after each test
‱ http://jasmine.github.io/2.0/introduction.
html#section-Spies
See autocomplete example in Sufia
https://github.com/projecthydra/sufia/blob/master/spec/javascripts/autocomplete_spec.js.coffee
Control Time
‱ jasmine.clock().install
‱ Starts and defines the Jasmine clock
‱ Makes calls to timer functions synchronous
‱ jasmine.clock().tick
‱ Allows you to move time forward
instantaneously
See autocomplete example in Sufia
https://github.com/projecthydra/sufia/blob/master/spec/javascripts/autocomplete_spec.js.coffee
‱ Run Jasmine in CI mode
‱ Capture the output
‱ Evaluate the output for failures
‱ Existing code is available in Sufia
‱ https://github.com/projecthydra/sufia/blob
/master/spec/javascripts/jasmine_spec.rb
‱ Would like to create a Gem or integrate
with another Gem
Jasmine add on to RSpec
Thanks!
Slides/code examples
https://github.com/hectorcorrea/riceonrails
Ad

Recommended

PDF
RSpec
Marco Otte-Witte
 
PDF
Excellent
Marco Otte-Witte
 
PDF
Rails is not just Ruby
Marco Otte-Witte
 
PDF
How to write easy-to-test JavaScript
Ynon Perek
 
PDF
Introduction to Protractor
Jie-Wei Wu
 
KEY
I18n
soon
 
PDF
Python for AngularJS
Jeff Schenck
 
PPTX
AngularJS for Java Developers
Loc Nguyen
 
PPTX
Dart and AngularDart
Loc Nguyen
 
PDF
Broadleaf Presents Thymeleaf
Broadleaf Commerce
 
PPTX
Top 10 Mistakes AngularJS Developers Make
Mark Meyer
 
PDF
Writing testable js [by Ted Piotrowski]
JavaScript Meetup HCMC
 
PPTX
AngularJS Architecture
Eyal Vardi
 
PPTX
React + Redux Introduction
Nikolaus Graf
 
PDF
Introduction to thymeleaf
NexThoughts Technologies
 
PPTX
Angularjs Anti-patterns
Steven Lambert
 
PDF
React.js or why DOM finally makes sense
Eldar Djafarov
 
PPTX
Introducing AngularJS
Loc Nguyen
 
PDF
React for Dummies
Mitch Chen
 
PPTX
Optimizing a large angular application (ng conf)
A K M Zahiduzzaman
 
PDF
Automated testing with RSpec
Nascenia IT
 
PDF
Thymeleaf Introduction
Anthony Chen
 
PDF
What's new in Django 1.7
Daniel Roseman
 
PDF
Unit testing JavaScript using Mocha and Node
Josh Mock
 
PDF
ХДргДĐč Đ‘ĐŸĐ»ŃŒŃ‰ĐžĐșĐŸĐČ "Protractor Tips & Tricks"
Fwdays
 
PDF
React.js and Redux overview
Alex Bachuk
 
PDF
What's New in Django 1.6
Siva Arunachalam
 
PPTX
Angularjs Basics
Anuradha Bandara
 
PDF
Test-Driven Development of AngularJS Applications
FITC
 
PDF
Angularjs Test Driven Development (TDD)
Anis Bouhachem Djer
 

More Related Content

What's hot (20)

PPTX
Dart and AngularDart
Loc Nguyen
 
PDF
Broadleaf Presents Thymeleaf
Broadleaf Commerce
 
PPTX
Top 10 Mistakes AngularJS Developers Make
Mark Meyer
 
PDF
Writing testable js [by Ted Piotrowski]
JavaScript Meetup HCMC
 
PPTX
AngularJS Architecture
Eyal Vardi
 
PPTX
React + Redux Introduction
Nikolaus Graf
 
PDF
Introduction to thymeleaf
NexThoughts Technologies
 
PPTX
Angularjs Anti-patterns
Steven Lambert
 
PDF
React.js or why DOM finally makes sense
Eldar Djafarov
 
PPTX
Introducing AngularJS
Loc Nguyen
 
PDF
React for Dummies
Mitch Chen
 
PPTX
Optimizing a large angular application (ng conf)
A K M Zahiduzzaman
 
PDF
Automated testing with RSpec
Nascenia IT
 
PDF
Thymeleaf Introduction
Anthony Chen
 
PDF
What's new in Django 1.7
Daniel Roseman
 
PDF
Unit testing JavaScript using Mocha and Node
Josh Mock
 
PDF
ХДргДĐč Đ‘ĐŸĐ»ŃŒŃ‰ĐžĐșĐŸĐČ "Protractor Tips & Tricks"
Fwdays
 
PDF
React.js and Redux overview
Alex Bachuk
 
PDF
What's New in Django 1.6
Siva Arunachalam
 
PPTX
Angularjs Basics
Anuradha Bandara
 
Dart and AngularDart
Loc Nguyen
 
Broadleaf Presents Thymeleaf
Broadleaf Commerce
 
Top 10 Mistakes AngularJS Developers Make
Mark Meyer
 
Writing testable js [by Ted Piotrowski]
JavaScript Meetup HCMC
 
AngularJS Architecture
Eyal Vardi
 
React + Redux Introduction
Nikolaus Graf
 
Introduction to thymeleaf
NexThoughts Technologies
 
Angularjs Anti-patterns
Steven Lambert
 
React.js or why DOM finally makes sense
Eldar Djafarov
 
Introducing AngularJS
Loc Nguyen
 
React for Dummies
Mitch Chen
 
Optimizing a large angular application (ng conf)
A K M Zahiduzzaman
 
Automated testing with RSpec
Nascenia IT
 
Thymeleaf Introduction
Anthony Chen
 
What's new in Django 1.7
Daniel Roseman
 
Unit testing JavaScript using Mocha and Node
Josh Mock
 
ХДргДĐč Đ‘ĐŸĐ»ŃŒŃ‰ĐžĐșĐŸĐČ "Protractor Tips & Tricks"
Fwdays
 
React.js and Redux overview
Alex Bachuk
 
What's New in Django 1.6
Siva Arunachalam
 
Angularjs Basics
Anuradha Bandara
 

Similar to Testing JavaScript with Jasmine in Rails Applications (20)

PDF
Test-Driven Development of AngularJS Applications
FITC
 
PDF
Angularjs Test Driven Development (TDD)
Anis Bouhachem Djer
 
PPTX
Javascript first-class citizenery
toddbr
 
PDF
Advanced Javascript Unit Testing
Lars Thorup
 
KEY
Javascript unit testing, yes we can e big
Andy Peterson
 
PPT
Automated javascript unit testing
ryan_chambers
 
PDF
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
Guy Royse
 
PDF
HTML5 for the Silverlight Guy
David Padbury
 
PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
PPTX
the next web now
zulin Gu
 
KEY
JavaScript Growing Up
David Padbury
 
PDF
Quick tour to front end unit testing using jasmine
Gil Fink
 
KEY
CoffeeScript - A Rubyist's Love Affair
Mark
 
PDF
Wt unit 2 ppts client side technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PDF
Wt unit 2 ppts client sied technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PPTX
Compatibility Detector Tool of Chrome extensions
Kai Cui
 
PPTX
Testing ASP.NET - Progressive.NET
Ben Hall
 
PPT
jQuery Objects
Steve Wells
 
PDF
Having Fun with Play
Clinton Dreisbach
 
PDF
Quality Assurance for PHP projects - ZendCon 2012
Michelangelo van Dam
 
Test-Driven Development of AngularJS Applications
FITC
 
Angularjs Test Driven Development (TDD)
Anis Bouhachem Djer
 
Javascript first-class citizenery
toddbr
 
Advanced Javascript Unit Testing
Lars Thorup
 
Javascript unit testing, yes we can e big
Andy Peterson
 
Automated javascript unit testing
ryan_chambers
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
Guy Royse
 
HTML5 for the Silverlight Guy
David Padbury
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
the next web now
zulin Gu
 
JavaScript Growing Up
David Padbury
 
Quick tour to front end unit testing using jasmine
Gil Fink
 
CoffeeScript - A Rubyist's Love Affair
Mark
 
Wt unit 2 ppts client side technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Wt unit 2 ppts client sied technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Compatibility Detector Tool of Chrome extensions
Kai Cui
 
Testing ASP.NET - Progressive.NET
Ben Hall
 
jQuery Objects
Steve Wells
 
Having Fun with Play
Clinton Dreisbach
 
Quality Assurance for PHP projects - ZendCon 2012
Michelangelo van Dam
 
Ad

Recently uploaded (20)

PPTX
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
PDF
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
PDF
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
PDF
Heat Treatment Process Automation in India
Reckers Mechatronics
 
PDF
Complete WordPress Programming Guidance Book
Shabista Imam
 
PDF
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
 
PDF
Y - Recursion The Hard Way GopherCon EU 2025
Eleanor McHugh
 
DOCX
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
PDF
Which Hiring Management Tools Offer the Best ROI?
HireME
 
PPTX
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
PPTX
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
PPTX
arctitecture application system design os dsa
za241967
 
PDF
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
PDF
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
Hassan Abid
 
PDF
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
 
PPT
Complete Guideliness to Build an Effective Maintenance Plan.ppt
QualityzeInc1
 
DOCX
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
PDF
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
PPTX
Simplify Insurance Regulations with Compliance Management Software
Insurance Tech Services
 
PDF
Sysinfo OST to PST Converter Infographic
SysInfo Tools
 
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
Heat Treatment Process Automation in India
Reckers Mechatronics
 
Complete WordPress Programming Guidance Book
Shabista Imam
 
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
 
Y - Recursion The Hard Way GopherCon EU 2025
Eleanor McHugh
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
Which Hiring Management Tools Offer the Best ROI?
HireME
 
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
arctitecture application system design os dsa
za241967
 
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
Hassan Abid
 
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
 
Complete Guideliness to Build an Effective Maintenance Plan.ppt
QualityzeInc1
 
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
Simplify Insurance Regulations with Compliance Management Software
Insurance Tech Services
 
Sysinfo OST to PST Converter Infographic
SysInfo Tools
 
Ad

Testing JavaScript with Jasmine in Rails Applications

  • 1. Testing JavaScript with Jasmine Carolyn Cole [email protected] Hector Correa [email protected] The Pennsylvania State University
  • 2. The Problem Testing JavaScript with Ruby tools is hard ‱ Feature Tests ‱ tend to be slow ‱ hard to test error cases ‱ View Tests ‱ do not test JavaScript
  • 4. The Solution ‱ Integrate a JavaScript Testing Framework ‱ There are many options ‱ Karma, QUnit, Buster, Mocha.js, Jasmine, 
 ‱ http://stackoverflow.com/questions/300855/javascri pt-unit-test-tools-for-tdd
  • 5. Why Jasmine? ‱ Easily integrated with existing tests ‱ Familiar syntax to RSpec ‱ Built in matchers ‱ Mock objects ‱ Control time
  • 6. Familiar Syntax - JavaScript JavaScript/Jasmine describe(”something", function() { beforeEach(function() { ... }); it(”does something", function() { ... }); }); Ruby/Rspec describe ”something" do before do ... end it "does something" do ... end end
  • 7. Familiar Syntax - CoffeeScript CoffeeScript/Jasmine describe ”something", -> beforeEach -> ... it "does something", -> ... Ruby/Rspec describe ”something" do before do ... end it "does something" do ... end end
  • 8. Running Jasmine ‱ User Interface $ rake jasmine > go to localhost:8888 to view results ‱ Continuous Integration $ rake jasmine:ci Waiting for jasmine server on 58458... jasmine server started .. 2 specs, 0 failures [2015-09-21 10:15:15] INFO going to shutdown ... [2015-09-21 10:15:15] INFO WEBrick::HTTPServer#start done
  • 9. Testing plain vanilla JavaScript // Calculator.js Calculator.addNumbers = function(a, b) { return a + b; } // CalculatorSpec.js describe("Calculator", function() { it("adds two numbers", function() { result = Calculator.addNumbers(4,5); expect(result).toEqual(9); }); });
  • 10. Testing DOM elements (1/2) // Calculator.js Calculator.updateUI = function() { var a = $("#number1").val(); var b = $("#number2").val(); var result = Calculator.addNumbers(a, b); $("#resultGoesHere").text(result); }
  • 11. Testing DOM elements (2/2) // CalculatorUISpec.js describe("Calculator UI", function() { it("updates the UI with the result", function() { var html = '<input id="number1" value="4"/> ' + '<input id="number2" value="3"/> ' + '<span id="resultGoesHere"/>'; setFixtures(html); Calculator.updateUI(); var result = $("#resultGoesHere"); expect(result.text()).toEqual("7"); }); });
  • 12. Expect and matchers ‱ Syntax similar to Rspec expect(result.text()).toEqual("7"); var button = $("#theButton"); expect(button).toBeDisabled();
  • 13. Matchers ‱ Built-in ‱ toMatch, not.toMatch, toBeDefined, not.toBeDefined, toBeNull, toBeTruthy, toContain, toEqual, ... ‱ http://jasmine.github.io/2.0/introduction.html ‱ Third party matchers (e.g. Jasmine jQuery) ‱ $(“#someID”) ‱ toBeDisabled, not.toBeDisabled, ... ‱ https://github.com/velesin/jasmine-jquery ‱ Write your own
  • 14. Mock Objects - Spies ‱ Spies can be used for any JavaScript function ‱ All calls and arguments to a spy are tracked ‱ It only exists in the block and will be removed after each test ‱ http://jasmine.github.io/2.0/introduction. html#section-Spies See autocomplete example in Sufia https://github.com/projecthydra/sufia/blob/master/spec/javascripts/autocomplete_spec.js.coffee
  • 15. Control Time ‱ jasmine.clock().install ‱ Starts and defines the Jasmine clock ‱ Makes calls to timer functions synchronous ‱ jasmine.clock().tick ‱ Allows you to move time forward instantaneously See autocomplete example in Sufia https://github.com/projecthydra/sufia/blob/master/spec/javascripts/autocomplete_spec.js.coffee
  • 16. ‱ Run Jasmine in CI mode ‱ Capture the output ‱ Evaluate the output for failures ‱ Existing code is available in Sufia ‱ https://github.com/projecthydra/sufia/blob /master/spec/javascripts/jasmine_spec.rb ‱ Would like to create a Gem or integrate with another Gem Jasmine add on to RSpec

Editor's Notes

  • #2: Poll the audience on Ruby/Rails/Spec/Sufia knowledge
  • #3: Because of this we were not testing our JavaScript and therefore it tended to be rather brittle.
  • #5: Test JavaScript like you would your Ruby unit tests. We picked because it integrates easily with Ruby but there are others too. The goal test our JavaScript, regardless of the framework.
  • #6: Ask people in the audience if they are familiar with RSpec. A lot of features that we are used to in Ruby.
  • #8: Twin orchids
  • #10: A simple check but very important to us.
  • #11: A simple check but very important to us.
  • #12: A simple check but very important to us.
  • #14: Jasmine jQuery - custom matchers for jQuery and an API for handling HTML, CSS, and JSON fixtures
  • #15: Spy is like a mock object on steroids. You can mock a REST API (e.g. auto-complete, single-use link in Sufia) spyOn($,"ajax")
  • #16: Allows to move time forward (useful when the actual code has delays). See autocomplete example in Sufia.
  • #17: Do this if you don't want to have to run two separate rake tasks: rake rspec + rake jasmine:ci We used to have RSpec and Cucumber. Cucumber was always forgotten. TODO: What does Cucumber do exactly? Runs the app as a user -- therefore it was very slow.