SlideShare a Scribd company logo
1 of 47
Download to read offline
1
Test Driven development
& Jasmine
Anup Singh
https://in.linkedin.com/in/anupsinghpune
Points to Discuss
• Unit Testing & Test Driven Development
• Debugging JS
• Writing Testable Code
• Designing own testing framework
• Jasmine
• Testing Forms
2https://in.linkedin.com/in/anupsinghpune
How do you test your JS?
1. Write your JavaScript code
2. See if it works in your favourite browser
3. Change something + [F5]
4. If it doesn't work repeat #3 until you make it work or you
go crazy...
5. In case you made it work, discover few days/weeks later
that it doesn't work in another browser
3https://in.linkedin.com/in/anupsinghpune
I think I'm going crazy...
4https://in.linkedin.com/in/anupsinghpune
Unit Testing
• In computer programming, unit testing is a
procedure used to validate that individual
modules or units of source code are working
properly.
• Unit testing is used for
(i) Test Driven Development
(ii) Fixing bugs
(iii) Regression testing
5https://in.linkedin.com/in/anupsinghpune
Test Driven Development
• Test-Driven Development (TDD) is a computer
programming technique that involves
repeatedly first writing a test case and then
implementing only the code necessary to pass
the test.
• Test-driven development is a method of
designing software, not merely a method of
testing.
6https://in.linkedin.com/in/anupsinghpune
Test Driven Development
• TDD in its simplest form is just this:
– Write your tests
– Watch them fail
– Make them pass
– Refactor
– Repeat
7https://in.linkedin.com/in/anupsinghpune
The TDD Micro-Cycle
8https://in.linkedin.com/in/anupsinghpune
Fixing bugs/Regression Testing
9
• Fixing bugs
• Regression testing
https://in.linkedin.com/in/anupsinghpune
What do you need?
• A Unit Testing framework
• Development Environment
10https://in.linkedin.com/in/anupsinghpune
Tools
 Firebug - The popular developer extension for Firefox that got the ball rolling.
See http://getfirebug.org/.
 IE Developer Tools - Included in Internet Explorer 8 and later.
 Opera Dragonfly - Included in Opera 9.5 and newer. Also works with mobile versions of Opera.
 WebKit Developer Tools - Introduced in Safari 3, dramatically improved as of Safari 4, and now available in Chrome.
Logging - http://patik.com/blog/complete-cross-browser-console-log/
1. alert()
2. Console.log()
3. Common logging method that for all modern browsers
function log() {
try {
console.log.apply(console, arguments);
} catch (e) {
try {
opera.postError.apply(opera, arguments);
} catch (e) {
alert(Array.prototype.join.call(arguments, " "));
}
}
}
1. Tries to log message using the
most common method
2. Catches any failure in logging
3. Tries to log the Opera way
Uses alert if all else fails
Testing and debugging - Debugging code
Breakpoints allow us to halt execution at a specific line of code so we can take a gander at the state.
<!DOCTYPE html>
<html>
<head>
<title>Listing 2.2</title>
<script type="text/javascript" src="log.js"></script>
<script type="text/javascript">
var x = 213;
log(x);
</script>
</head>
<body>
</body>
</html>
Testing and debugging - Breakpoints
https://in.linkedin.com/in/anupsinghpune
Good tests make Good code - Emphasis on the word good.
It's quite possible to have an extensive test suite that doesn't really help the quality of our
code, if the tests are poorly constructed.
Good tests exhibit three important characteristics:
1. Repeatability - Our test results should be highly reproducible. Tests run repeatedly should always produce
the exact same results. If test results are nondeterministic, how would we know which results are valid and which
are invalid?
2. Simplicity - Our tests should focus on testing one thing. We should strive to remove as much HTML markup,
CSS, or JavaScript as we can without disrupting the intent of the test case. The more we remove, the greater the
likelihood that the test case will only be influenced by the specific code that we’re testing.
3. Independence - Our tests should execute in isolation. We must avoid making the results from one test
dependent upon another. Breaking tests down into the smallest possible
Test generation
https://in.linkedin.com/in/anupsinghpune
A test suite should serve as a fundamental part of your development workflow, so you
should pick a suite that works particularly well for your coding style and your
code
base.
JavaScript unit testing framework features
• The ability to simulate browser behaviour (clicks, keypresses, and so on)
• Interactive control of tests (pausing and resuming tests)
• Handling asynchronous test timeouts
• The ability to filter which tests are to be executed
Testing Frameworks
https://in.linkedin.com/in/anupsinghpune
Market Share of Testing frameworks
15https://in.linkedin.com/in/anupsinghpune
The fundamentals of a test suite
The fundamentals of a test suite
1. Aggregate all the individual tests into a single unit
2. Run the in Bulk
3. Providing a single resource that can be run easily and repeatedly
How to construct a test suite
Q. Why would I want to build a new test suite, When There are already a number of good-quality suites
to choose from?
A. Building your own test suite can serve as a good learning experience, especially when looking at how
asynchronous testing works.
16https://in.linkedin.com/in/anupsinghpune
The Assertion – (assert.html)
17
1. The core of a unit-testing framework is its assertion method, usually named
assert().
2. This takes a value—an expression whose premise is asserted—and a
description that describes the purpose of the assertion. If the value
evaluates to true
3. Either the assertion passes or it’s considered a failure.
4. The associated message is usually logged with an appropriate pass/fail
indicator.
https://in.linkedin.com/in/anupsinghpune
Simple Implementation of JavaScript
Assertion
18https://in.linkedin.com/in/anupsinghpune
More Examples -
• Custom/1_jq_test.html
• Custom/assert.html
• Custom/test_group.html
19https://in.linkedin.com/in/anupsinghpune
Test Groups – (test_group.html)
1. Grouping assertions together in a testing context to form test
groups.
2. Test group will likely represent a collection of assertions as they
relate to a single method in our API or application
3. If any assertion fails, then the entire test group is marked as failing
20https://in.linkedin.com/in/anupsinghpune
So what's the first step to sanity?
WRITE TESTABLE CODE
21https://in.linkedin.com/in/anupsinghpune
What's wrong with this code?
js_sample_001.js
(inline functions and more inside, ajax
directly hooked to element, etc.)
22https://in.linkedin.com/in/anupsinghpune
Anonymous functions, within functions,
within functions...
23https://in.linkedin.com/in/anupsinghpune
I'll put functions in your functions...
24https://in.linkedin.com/in/anupsinghpune
All your DOM elements are belong to JS!
25https://in.linkedin.com/in/anupsinghpune
Server URL coupling
js_sample_001.js
(with highlighted hardcoded url)
26https://in.linkedin.com/in/anupsinghpune
Refactoring...
js_sample_002.js
27https://in.linkedin.com/in/anupsinghpune
Refactoring...
js_sample_002.js
28https://in.linkedin.com/in/anupsinghpune
Now that's better...
29
js_sample_003.js
(init func and hooked named functions to
page)
https://in.linkedin.com/in/anupsinghpune
Now that's better...
30https://in.linkedin.com/in/anupsinghpune
Now that's better...
31https://in.linkedin.com/in/anupsinghpune
Now what about testing?
Popular JS Unit-testing frameworks:
 QUnit
 Jasmine
 UnitJS
 JsUnit (no longer actively maintained)
 Some other – see:
http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#JavaScript
32https://in.linkedin.com/in/anupsinghpune
Introducing Jasmine
• Testing framework
• Suites possess a hierarchical structure
• Tests as specifications
• Matchers, both built-in and custom
• Spies, a test double pattern
33https://in.linkedin.com/in/anupsinghpune
Jasmine suite
describe("A specification suite", function() {
…
});
• Group specifications together using nested
describe function blocks.
• Also useful for delineating context-specific
specifications.
34https://in.linkedin.com/in/anupsinghpune
Jasmine specification
describe("A specification suite", function() {
it(“contains spec with an expectation", function() {
expect(view.tagName).toBe(‘tr’);
});
});
• Specifications are expressed with the it function.
• The description should read well in the report.
• Expectations are expressed with the expect
function
35https://in.linkedin.com/in/anupsinghpune
• The describe function, describes a feature of an application. It acts as an
aggregating container for individual tests. You can think of the describe blocks as of
test suites. The describe blocks can be nested inside each other.
• The test itself is located inside the it function. The idea is to exercise one particular
aspect of a feature in one test. A test has a name and a body. Usually the first section
of the test's body calls methods on an object under test while the later one verifies
expected results.
• Code contained in the beforeEach block will get executed before each individual
test. This is a perfect place for any initialization logic that has to be executed before
each test.
• The last things to mention are the expect and the toEqual functions. Using those
two constructs we can compare actual results with the expected ones. Jasmine,
comes with a rich set of matchers, toBeTruthy, toBeDefined, toContain are just
few examples of what is available.
Jasmine specification
36https://in.linkedin.com/in/anupsinghpune
Jasmine matchers
• not
• toBe
• toEqual
• toMatch
• toBeDefined
• toBeUndefined
• toBeNull
• toBeTruthy
• toBeFalsy
• toContain
• toBeLessThan
• toBeGreaterThan
• toBeCloseTo
• toThrow
37https://in.linkedin.com/in/anupsinghpune
Jasmine setup using beforeEach
describe("PintailConsulting.ToDoListView", function() {
var view;
beforeEach(function(){
view = new PintailConsulting.ToDoListView();
});
it(“sets the tagName to ‘div’", function() {
expect(view.tagName).toBe(‘div’);
});
});
38https://in.linkedin.com/in/anupsinghpune
Jasmine tear down using afterEach
describe("PintailConsulting.ToDoListView", function() {
var view;
beforeEach(function(){
view = new PintailConsulting.ToDoListView();
});
afterEach(function(){
view = null;
});
it(“sets the tagName to ‘div’", function() {
expect(view.tagName).toBe(‘div’);
});
});
39https://in.linkedin.com/in/anupsinghpune
Jasmine custom matchers
beforeEach(function() {
this.addMatchers({
toBeLessThan: function(expected) {
var actual = this.actual;
var notText = this.isNot ? " not" : "";
this.message = function () {
return "Expected " + actual + notText + " to be less than " +
expected;
}
return actual < expected;
}
});
});
40https://in.linkedin.com/in/anupsinghpune
Jasmine spies
• Test double pattern.
• Interception-based test double mechanism provided by the
Jasmine library.
• Spies record invocations and invocation parameters, allowing you
to inspect the spy after exercising the SUT.
• Very similar to mock objects.
• More information at
https://github.com/pivotal/jasmine/wiki/Spies.
41https://in.linkedin.com/in/anupsinghpune
Jasmine spy usage
Spying and verifying invocation
var spy = spyOn(dependency, “render”);
systemUnderTest.display();
expect(spy).toHaveBeenCalled();
Spying, verifying invocation and argument(s)
var spy = spyOn(dependency, “render”);
systemUnderTest.display(“Hello”);
expect(spy).toHaveBeenCalledWith(“Hello”);
42https://in.linkedin.com/in/anupsinghpune
Jasmine spy usage
Spying, verifying number of invocations and
arguments for each call
var spy = spyOn(Leaflet, “circle”).andCallThrough();
mapView.processResults(earthquakeJsonResults);
expect(spy).toHaveBeenCalled()
expect(circleConstructorSpy.callCount).toBe(2);
expect(circleConstructorSpy.argsForCall[0][0]).toEqual([56.681
2, -155.0237])
43https://in.linkedin.com/in/anupsinghpune
Loose matching with jasmine.any
• Accepts a constructor or “class” name as an expected
value.
• Returns true if the constructor matches the constructor of
the actual value.
var spy = jasmine.createSpy(My.Namespace, ’foo’);
foo(12, function(x) { return x * x; });
expect(spy).toHaveBeenCalledWith
(jasmine.any(Number), jasmine.any(Function));
44https://in.linkedin.com/in/anupsinghpune
Jasmine spy usage
• andCallThrough(): Allows the invocation to
passthrough to the real subject.
• andReturn(result): Return a hard-coded result.
• andCallFake(fakeImplFunction): Return a
dynamically generated result from a function.
• createSpy(identity): Manually create a spy.
• createSpyObj(identity, propertiesArray): Creates a
mock with multiple property spies.
45https://in.linkedin.com/in/anupsinghpune
Jasmine asynchronous support
• Use runs and waitsFor blocks and a latch function.
• The latch function polls until it returns true or the
timeout expires, whichever comes first.
• If the timeout expires, the specification fails with a
message.
• Kind of clunky to use.
46https://in.linkedin.com/in/anupsinghpune
Jasmine asynchronous example
describe("an async spec", function() {
var done;
beforeEach(function() {
done = false;
var doStuff = function() {
// simulate async stuff and wait 10ms
setTimeout(function() { done = true; }, 10);
};
runs(doStuff);
waitsFor(function() { return done; }, ‘The doStuff function should be done by
now.’, 100);
});
it("did stuff", function() {
expect(done).toBe(true);
});
});
47https://in.linkedin.com/in/anupsinghpune

More Related Content

What's hot

Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkArulalan T
 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasminefoxp2code
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails AppsRabble .
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSJim Lynch
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSKnoldus Inc.
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with JestMichał Pierzchała
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineGil Fink
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introductionNir Kaufman
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmineTimothy Oxley
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit TestChiew Carol
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JSMichael Haberman
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testingsgleadow
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesHarry Potter
 
Unit Test Your Database
Unit Test Your DatabaseUnit Test Your Database
Unit Test Your DatabaseDavid Wheeler
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtestWill Shen
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsFITC
 

What's hot (20)

Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasmine
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
 
Jasmine BDD for Javascript
Jasmine BDD for JavascriptJasmine BDD for Javascript
Jasmine BDD for Javascript
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
Angular testing
Angular testingAngular testing
Angular testing
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmine
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit Test
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JS
 
Unit Testing in iOS
Unit Testing in iOSUnit Testing in iOS
Unit Testing in iOS
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testing
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Unit Test Your Database
Unit Test Your DatabaseUnit Test Your Database
Unit Test Your Database
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 

Viewers also liked

CasperJS and PhantomJS for Automated Testing
CasperJS and PhantomJS for Automated TestingCasperJS and PhantomJS for Automated Testing
CasperJS and PhantomJS for Automated TestingX-Team
 
Javascript Unit Testing Tools
Javascript Unit Testing ToolsJavascript Unit Testing Tools
Javascript Unit Testing ToolsPixelCrayons
 
Automated Testing With Jasmine, PhantomJS and Jenkins
Automated Testing With Jasmine, PhantomJS and JenkinsAutomated Testing With Jasmine, PhantomJS and Jenkins
Automated Testing With Jasmine, PhantomJS and JenkinsWork at Play
 
Javascript unit tests with angular 1.x
Javascript unit tests with angular 1.xJavascript unit tests with angular 1.x
Javascript unit tests with angular 1.xRon Apelbaum
 
Site Testing with CasperJS
Site Testing with CasperJSSite Testing with CasperJS
Site Testing with CasperJSJoseph Scott
 
Test driven development
Test driven developmentTest driven development
Test driven developmentDennis Ahaus
 
Angular testing
Angular testingAngular testing
Angular testingYu Jin
 
Developer Experience to Testing
Developer Experience to TestingDeveloper Experience to Testing
Developer Experience to TestingMozaic Works
 
Testing javascript in the frontend
Testing javascript in the frontendTesting javascript in the frontend
Testing javascript in the frontendFrederic CABASSUT
 
JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit TestingKeir Bowden
 
Unit Testing Lightning Components with Jasmine
Unit Testing Lightning Components with JasmineUnit Testing Lightning Components with Jasmine
Unit Testing Lightning Components with JasmineKeir Bowden
 
The Developer Experience
The Developer ExperienceThe Developer Experience
The Developer ExperienceAtlassian
 
Introducing Sencha Touch 2
Introducing Sencha Touch 2Introducing Sencha Touch 2
Introducing Sencha Touch 2Sencha
 
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven DevelopmentABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven DevelopmentHendrik Neumann
 
Test Driven Development (TDD) & Continuous Integration (CI)
Test Driven Development (TDD) & Continuous Integration (CI)Test Driven Development (TDD) & Continuous Integration (CI)
Test Driven Development (TDD) & Continuous Integration (CI)Fatkul Amri
 
Test Driven Development SpeedRun
Test Driven Development SpeedRunTest Driven Development SpeedRun
Test Driven Development SpeedRunSpeck&Tech
 
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, 2016How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016Gavin Pickin
 
Javascript testing: tools of the trade
Javascript testing: tools of the tradeJavascript testing: tools of the trade
Javascript testing: tools of the tradeJuanma Orta
 

Viewers also liked (20)

CasperJS and PhantomJS for Automated Testing
CasperJS and PhantomJS for Automated TestingCasperJS and PhantomJS for Automated Testing
CasperJS and PhantomJS for Automated Testing
 
Javascript Unit Testing Tools
Javascript Unit Testing ToolsJavascript Unit Testing Tools
Javascript Unit Testing Tools
 
jasmine
jasminejasmine
jasmine
 
Automated Testing With Jasmine, PhantomJS and Jenkins
Automated Testing With Jasmine, PhantomJS and JenkinsAutomated Testing With Jasmine, PhantomJS and Jenkins
Automated Testing With Jasmine, PhantomJS and Jenkins
 
Javascript unit tests with angular 1.x
Javascript unit tests with angular 1.xJavascript unit tests with angular 1.x
Javascript unit tests with angular 1.x
 
Site Testing with CasperJS
Site Testing with CasperJSSite Testing with CasperJS
Site Testing with CasperJS
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
CasperJS
CasperJSCasperJS
CasperJS
 
Angular testing
Angular testingAngular testing
Angular testing
 
Developer Experience to Testing
Developer Experience to TestingDeveloper Experience to Testing
Developer Experience to Testing
 
Testing javascript in the frontend
Testing javascript in the frontendTesting javascript in the frontend
Testing javascript in the frontend
 
JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit Testing
 
Unit Testing Lightning Components with Jasmine
Unit Testing Lightning Components with JasmineUnit Testing Lightning Components with Jasmine
Unit Testing Lightning Components with Jasmine
 
The Developer Experience
The Developer ExperienceThe Developer Experience
The Developer Experience
 
Introducing Sencha Touch 2
Introducing Sencha Touch 2Introducing Sencha Touch 2
Introducing Sencha Touch 2
 
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven DevelopmentABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
 
Test Driven Development (TDD) & Continuous Integration (CI)
Test Driven Development (TDD) & Continuous Integration (CI)Test Driven Development (TDD) & Continuous Integration (CI)
Test Driven Development (TDD) & Continuous Integration (CI)
 
Test Driven Development SpeedRun
Test Driven Development SpeedRunTest Driven Development SpeedRun
Test Driven Development SpeedRun
 
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, 2016How 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
 
Javascript testing: tools of the trade
Javascript testing: tools of the tradeJavascript testing: tools of the trade
Javascript testing: tools of the trade
 

Similar to JAVASCRIPT Test Driven Development & Jasmine

RIA 05 - Unit Testing by Ajinkya Prabhune
RIA 05 - Unit Testing by Ajinkya PrabhuneRIA 05 - Unit Testing by Ajinkya Prabhune
RIA 05 - Unit Testing by Ajinkya PrabhuneJohannes Hoppe
 
Software Testing
Software TestingSoftware Testing
Software TestingAdroitLogic
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosFlutter Agency
 
Testing Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksTesting Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksŁukasz Morawski
 
Cypress Best Pratices for Test Automation
Cypress Best Pratices for Test AutomationCypress Best Pratices for Test Automation
Cypress Best Pratices for Test AutomationKnoldus Inc.
 
QTP 10.0_Kalyan Chakravarthy.ppt
QTP 10.0_Kalyan Chakravarthy.pptQTP 10.0_Kalyan Chakravarthy.ppt
QTP 10.0_Kalyan Chakravarthy.pptKalyan Chakravarthy
 
Hadoop testing workshop - july 2013
Hadoop testing workshop - july 2013Hadoop testing workshop - july 2013
Hadoop testing workshop - july 2013Ophir Cohen
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
Software Test Automation - Best Practices
Software Test Automation - Best PracticesSoftware Test Automation - Best Practices
Software Test Automation - Best PracticesArul Selvan
 
Test automation principles, terminologies and implementations
Test automation principles, terminologies and implementationsTest automation principles, terminologies and implementations
Test automation principles, terminologies and implementationsSteven Li
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4Billie Berzinskas
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with SeleniumDave Haeffner
 
Lecture (Software Testing).pptx
Lecture (Software Testing).pptxLecture (Software Testing).pptx
Lecture (Software Testing).pptxskknowledge
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkOnkar Deshpande
 
M. Holovaty, Концепции автоматизированного тестирования
M. Holovaty, Концепции автоматизированного тестированияM. Holovaty, Концепции автоматизированного тестирования
M. Holovaty, Концепции автоматизированного тестированияAlex
 

Similar to JAVASCRIPT Test Driven Development & Jasmine (20)

Automation using ibm rft
Automation using ibm rftAutomation using ibm rft
Automation using ibm rft
 
RIA 05 - Unit Testing by Ajinkya Prabhune
RIA 05 - Unit Testing by Ajinkya PrabhuneRIA 05 - Unit Testing by Ajinkya Prabhune
RIA 05 - Unit Testing by Ajinkya Prabhune
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
 
Review of an open source unit test tool- Cucumber_Presentation
Review of an open source unit test tool- Cucumber_PresentationReview of an open source unit test tool- Cucumber_Presentation
Review of an open source unit test tool- Cucumber_Presentation
 
Testing Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksTesting Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation Frameworks
 
Software engg unit 4
Software engg unit 4 Software engg unit 4
Software engg unit 4
 
Cypress Best Pratices for Test Automation
Cypress Best Pratices for Test AutomationCypress Best Pratices for Test Automation
Cypress Best Pratices for Test Automation
 
QTP 10.0_Kalyan Chakravarthy.ppt
QTP 10.0_Kalyan Chakravarthy.pptQTP 10.0_Kalyan Chakravarthy.ppt
QTP 10.0_Kalyan Chakravarthy.ppt
 
jDriver Presentation
jDriver PresentationjDriver Presentation
jDriver Presentation
 
Hadoop testing workshop - july 2013
Hadoop testing workshop - july 2013Hadoop testing workshop - july 2013
Hadoop testing workshop - july 2013
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Software Test Automation - Best Practices
Software Test Automation - Best PracticesSoftware Test Automation - Best Practices
Software Test Automation - Best Practices
 
Test automation principles, terminologies and implementations
Test automation principles, terminologies and implementationsTest automation principles, terminologies and implementations
Test automation principles, terminologies and implementations
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with Selenium
 
Lecture (Software Testing).pptx
Lecture (Software Testing).pptxLecture (Software Testing).pptx
Lecture (Software Testing).pptx
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
M. Holovaty, Концепции автоматизированного тестирования
M. Holovaty, Концепции автоматизированного тестированияM. Holovaty, Концепции автоматизированного тестирования
M. Holovaty, Концепции автоматизированного тестирования
 

Recently uploaded

Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 

Recently uploaded (20)

Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 

JAVASCRIPT Test Driven Development & Jasmine

  • 1. 1 Test Driven development & Jasmine Anup Singh https://in.linkedin.com/in/anupsinghpune
  • 2. Points to Discuss • Unit Testing & Test Driven Development • Debugging JS • Writing Testable Code • Designing own testing framework • Jasmine • Testing Forms 2https://in.linkedin.com/in/anupsinghpune
  • 3. How do you test your JS? 1. Write your JavaScript code 2. See if it works in your favourite browser 3. Change something + [F5] 4. If it doesn't work repeat #3 until you make it work or you go crazy... 5. In case you made it work, discover few days/weeks later that it doesn't work in another browser 3https://in.linkedin.com/in/anupsinghpune
  • 4. I think I'm going crazy... 4https://in.linkedin.com/in/anupsinghpune
  • 5. Unit Testing • In computer programming, unit testing is a procedure used to validate that individual modules or units of source code are working properly. • Unit testing is used for (i) Test Driven Development (ii) Fixing bugs (iii) Regression testing 5https://in.linkedin.com/in/anupsinghpune
  • 6. Test Driven Development • Test-Driven Development (TDD) is a computer programming technique that involves repeatedly first writing a test case and then implementing only the code necessary to pass the test. • Test-driven development is a method of designing software, not merely a method of testing. 6https://in.linkedin.com/in/anupsinghpune
  • 7. Test Driven Development • TDD in its simplest form is just this: – Write your tests – Watch them fail – Make them pass – Refactor – Repeat 7https://in.linkedin.com/in/anupsinghpune
  • 9. Fixing bugs/Regression Testing 9 • Fixing bugs • Regression testing https://in.linkedin.com/in/anupsinghpune
  • 10. What do you need? • A Unit Testing framework • Development Environment 10https://in.linkedin.com/in/anupsinghpune
  • 11. Tools  Firebug - The popular developer extension for Firefox that got the ball rolling. See http://getfirebug.org/.  IE Developer Tools - Included in Internet Explorer 8 and later.  Opera Dragonfly - Included in Opera 9.5 and newer. Also works with mobile versions of Opera.  WebKit Developer Tools - Introduced in Safari 3, dramatically improved as of Safari 4, and now available in Chrome. Logging - http://patik.com/blog/complete-cross-browser-console-log/ 1. alert() 2. Console.log() 3. Common logging method that for all modern browsers function log() { try { console.log.apply(console, arguments); } catch (e) { try { opera.postError.apply(opera, arguments); } catch (e) { alert(Array.prototype.join.call(arguments, " ")); } } } 1. Tries to log message using the most common method 2. Catches any failure in logging 3. Tries to log the Opera way Uses alert if all else fails Testing and debugging - Debugging code
  • 12. Breakpoints allow us to halt execution at a specific line of code so we can take a gander at the state. <!DOCTYPE html> <html> <head> <title>Listing 2.2</title> <script type="text/javascript" src="log.js"></script> <script type="text/javascript"> var x = 213; log(x); </script> </head> <body> </body> </html> Testing and debugging - Breakpoints https://in.linkedin.com/in/anupsinghpune
  • 13. Good tests make Good code - Emphasis on the word good. It's quite possible to have an extensive test suite that doesn't really help the quality of our code, if the tests are poorly constructed. Good tests exhibit three important characteristics: 1. Repeatability - Our test results should be highly reproducible. Tests run repeatedly should always produce the exact same results. If test results are nondeterministic, how would we know which results are valid and which are invalid? 2. Simplicity - Our tests should focus on testing one thing. We should strive to remove as much HTML markup, CSS, or JavaScript as we can without disrupting the intent of the test case. The more we remove, the greater the likelihood that the test case will only be influenced by the specific code that we’re testing. 3. Independence - Our tests should execute in isolation. We must avoid making the results from one test dependent upon another. Breaking tests down into the smallest possible Test generation https://in.linkedin.com/in/anupsinghpune
  • 14. A test suite should serve as a fundamental part of your development workflow, so you should pick a suite that works particularly well for your coding style and your code base. JavaScript unit testing framework features • The ability to simulate browser behaviour (clicks, keypresses, and so on) • Interactive control of tests (pausing and resuming tests) • Handling asynchronous test timeouts • The ability to filter which tests are to be executed Testing Frameworks https://in.linkedin.com/in/anupsinghpune
  • 15. Market Share of Testing frameworks 15https://in.linkedin.com/in/anupsinghpune
  • 16. The fundamentals of a test suite The fundamentals of a test suite 1. Aggregate all the individual tests into a single unit 2. Run the in Bulk 3. Providing a single resource that can be run easily and repeatedly How to construct a test suite Q. Why would I want to build a new test suite, When There are already a number of good-quality suites to choose from? A. Building your own test suite can serve as a good learning experience, especially when looking at how asynchronous testing works. 16https://in.linkedin.com/in/anupsinghpune
  • 17. The Assertion – (assert.html) 17 1. The core of a unit-testing framework is its assertion method, usually named assert(). 2. This takes a value—an expression whose premise is asserted—and a description that describes the purpose of the assertion. If the value evaluates to true 3. Either the assertion passes or it’s considered a failure. 4. The associated message is usually logged with an appropriate pass/fail indicator. https://in.linkedin.com/in/anupsinghpune
  • 18. Simple Implementation of JavaScript Assertion 18https://in.linkedin.com/in/anupsinghpune
  • 19. More Examples - • Custom/1_jq_test.html • Custom/assert.html • Custom/test_group.html 19https://in.linkedin.com/in/anupsinghpune
  • 20. Test Groups – (test_group.html) 1. Grouping assertions together in a testing context to form test groups. 2. Test group will likely represent a collection of assertions as they relate to a single method in our API or application 3. If any assertion fails, then the entire test group is marked as failing 20https://in.linkedin.com/in/anupsinghpune
  • 21. So what's the first step to sanity? WRITE TESTABLE CODE 21https://in.linkedin.com/in/anupsinghpune
  • 22. What's wrong with this code? js_sample_001.js (inline functions and more inside, ajax directly hooked to element, etc.) 22https://in.linkedin.com/in/anupsinghpune
  • 23. Anonymous functions, within functions, within functions... 23https://in.linkedin.com/in/anupsinghpune
  • 24. I'll put functions in your functions... 24https://in.linkedin.com/in/anupsinghpune
  • 25. All your DOM elements are belong to JS! 25https://in.linkedin.com/in/anupsinghpune
  • 26. Server URL coupling js_sample_001.js (with highlighted hardcoded url) 26https://in.linkedin.com/in/anupsinghpune
  • 29. Now that's better... 29 js_sample_003.js (init func and hooked named functions to page) https://in.linkedin.com/in/anupsinghpune
  • 32. Now what about testing? Popular JS Unit-testing frameworks:  QUnit  Jasmine  UnitJS  JsUnit (no longer actively maintained)  Some other – see: http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#JavaScript 32https://in.linkedin.com/in/anupsinghpune
  • 33. Introducing Jasmine • Testing framework • Suites possess a hierarchical structure • Tests as specifications • Matchers, both built-in and custom • Spies, a test double pattern 33https://in.linkedin.com/in/anupsinghpune
  • 34. Jasmine suite describe("A specification suite", function() { … }); • Group specifications together using nested describe function blocks. • Also useful for delineating context-specific specifications. 34https://in.linkedin.com/in/anupsinghpune
  • 35. Jasmine specification describe("A specification suite", function() { it(“contains spec with an expectation", function() { expect(view.tagName).toBe(‘tr’); }); }); • Specifications are expressed with the it function. • The description should read well in the report. • Expectations are expressed with the expect function 35https://in.linkedin.com/in/anupsinghpune
  • 36. • The describe function, describes a feature of an application. It acts as an aggregating container for individual tests. You can think of the describe blocks as of test suites. The describe blocks can be nested inside each other. • The test itself is located inside the it function. The idea is to exercise one particular aspect of a feature in one test. A test has a name and a body. Usually the first section of the test's body calls methods on an object under test while the later one verifies expected results. • Code contained in the beforeEach block will get executed before each individual test. This is a perfect place for any initialization logic that has to be executed before each test. • The last things to mention are the expect and the toEqual functions. Using those two constructs we can compare actual results with the expected ones. Jasmine, comes with a rich set of matchers, toBeTruthy, toBeDefined, toContain are just few examples of what is available. Jasmine specification 36https://in.linkedin.com/in/anupsinghpune
  • 37. Jasmine matchers • not • toBe • toEqual • toMatch • toBeDefined • toBeUndefined • toBeNull • toBeTruthy • toBeFalsy • toContain • toBeLessThan • toBeGreaterThan • toBeCloseTo • toThrow 37https://in.linkedin.com/in/anupsinghpune
  • 38. Jasmine setup using beforeEach describe("PintailConsulting.ToDoListView", function() { var view; beforeEach(function(){ view = new PintailConsulting.ToDoListView(); }); it(“sets the tagName to ‘div’", function() { expect(view.tagName).toBe(‘div’); }); }); 38https://in.linkedin.com/in/anupsinghpune
  • 39. Jasmine tear down using afterEach describe("PintailConsulting.ToDoListView", function() { var view; beforeEach(function(){ view = new PintailConsulting.ToDoListView(); }); afterEach(function(){ view = null; }); it(“sets the tagName to ‘div’", function() { expect(view.tagName).toBe(‘div’); }); }); 39https://in.linkedin.com/in/anupsinghpune
  • 40. Jasmine custom matchers beforeEach(function() { this.addMatchers({ toBeLessThan: function(expected) { var actual = this.actual; var notText = this.isNot ? " not" : ""; this.message = function () { return "Expected " + actual + notText + " to be less than " + expected; } return actual < expected; } }); }); 40https://in.linkedin.com/in/anupsinghpune
  • 41. Jasmine spies • Test double pattern. • Interception-based test double mechanism provided by the Jasmine library. • Spies record invocations and invocation parameters, allowing you to inspect the spy after exercising the SUT. • Very similar to mock objects. • More information at https://github.com/pivotal/jasmine/wiki/Spies. 41https://in.linkedin.com/in/anupsinghpune
  • 42. Jasmine spy usage Spying and verifying invocation var spy = spyOn(dependency, “render”); systemUnderTest.display(); expect(spy).toHaveBeenCalled(); Spying, verifying invocation and argument(s) var spy = spyOn(dependency, “render”); systemUnderTest.display(“Hello”); expect(spy).toHaveBeenCalledWith(“Hello”); 42https://in.linkedin.com/in/anupsinghpune
  • 43. Jasmine spy usage Spying, verifying number of invocations and arguments for each call var spy = spyOn(Leaflet, “circle”).andCallThrough(); mapView.processResults(earthquakeJsonResults); expect(spy).toHaveBeenCalled() expect(circleConstructorSpy.callCount).toBe(2); expect(circleConstructorSpy.argsForCall[0][0]).toEqual([56.681 2, -155.0237]) 43https://in.linkedin.com/in/anupsinghpune
  • 44. Loose matching with jasmine.any • Accepts a constructor or “class” name as an expected value. • Returns true if the constructor matches the constructor of the actual value. var spy = jasmine.createSpy(My.Namespace, ’foo’); foo(12, function(x) { return x * x; }); expect(spy).toHaveBeenCalledWith (jasmine.any(Number), jasmine.any(Function)); 44https://in.linkedin.com/in/anupsinghpune
  • 45. Jasmine spy usage • andCallThrough(): Allows the invocation to passthrough to the real subject. • andReturn(result): Return a hard-coded result. • andCallFake(fakeImplFunction): Return a dynamically generated result from a function. • createSpy(identity): Manually create a spy. • createSpyObj(identity, propertiesArray): Creates a mock with multiple property spies. 45https://in.linkedin.com/in/anupsinghpune
  • 46. Jasmine asynchronous support • Use runs and waitsFor blocks and a latch function. • The latch function polls until it returns true or the timeout expires, whichever comes first. • If the timeout expires, the specification fails with a message. • Kind of clunky to use. 46https://in.linkedin.com/in/anupsinghpune
  • 47. Jasmine asynchronous example describe("an async spec", function() { var done; beforeEach(function() { done = false; var doStuff = function() { // simulate async stuff and wait 10ms setTimeout(function() { done = true; }, 10); }; runs(doStuff); waitsFor(function() { return done; }, ‘The doStuff function should be done by now.’, 100); }); it("did stuff", function() { expect(done).toBe(true); }); }); 47https://in.linkedin.com/in/anupsinghpune