SlideShare une entreprise Scribd logo
1  sur  45
Télécharger pour lire hors ligne
Javascript Unit Testing with xUnit.js
Building cleaner APIs, faster!
John Buchanan, salesforce.com, inc.
Lead Member of Technical Staff
Safe harbor
Safe harbor statement under the Private Securities Litigation Reform Act of 1995:
This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties
materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results
expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be
deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other
financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any
statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services.
The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new
functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our
operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of any
litigation, risks associated with completed and any possible mergers and acquisitions, the immature market in which we operate, our
relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our
service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to
larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is
included in our annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most recent
fiscal quarter. These documents and others containing important disclosures are available on the SEC Filings section of the Investor
Information section of our Web site.
Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently
available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions
based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these
forward-looking statements.
Challenges:
1. What are some of the problems with testing javascript?
Challenges:
1. What are some of the problems with testing javascript?
• Boundary Control (Web requests, DOM access)
Challenges:
1. What are some of the problems with testing javascript?
• Boundary Control (Web requests, DOM access)
• Automation / Continuous Integration
Challenges:
1. What are some of the problems with testing javascript?
• Boundary Control (Web requests, DOM access)
• Automation / Continuous Integration
• Design Dependencies, Encapsulation
Challenges:
2. What are the differences between unit and integration tests?
Challenges:
2. What are the differences between unit and integration tests?
• Single module or component vs. interactions between modules
Challenges:
2. What are the differences between unit and integration tests?
• Single module or component vs. interactions between modules
• Boundary Control (Web requests, DOM access)
Challenges:
2. What are the differences between unit and integration tests?
• Single module or component vs. interactions between modules
• Boundary Control (Web requests, DOM access)
• Cost to exercise in automation: Unit tests are cheap
Challenges:
2. What are the differences between unit and integration tests?
• Single module or component vs. interactions between modules
• Boundary Control (Web requests, DOM access)
• Cost to exercise in automation: Unit tests are cheap
• Dependencies are abstracted in units, included in integrations
xUnit.js
So what is

xUnit.js?
xUnit.js
A Host-Agnostic Test Engine with an
Attribution Based Console Runner
lolwut.
A brief history of

xUnit.js
xUnit.js:
• Started in 2006, open source project hosted on CodePlex
• Frustrated with typical test registration systems
• Environmental requirements were expensive (Server, browser)
• Loved the simplicity and speed of the WSH (cscript.exe)
• Starting to understand using unit tests as a design tool
Unit Tests:
• Should be easily organizable
• Must to be simple to add, minimizing “dev bounce”
• Need to be easy to run, but also run fast
• Should help enforce dependency isolation
• Could allow for custom types of decoration (Ignore, Test Category,
etc.)
Host Agnostic:
• Should support common hosts out of the box:
•Google Chrome (V8)
•Mozilla Firefox (SpiderMonkey)
•Microsoft Internet Explorer 4-11 (JScript and Chakra, via cscript.exe)
•Mozilla Rhino
• Must also be able to easily add new and special use hosts:
•JSDB
•NodeJS
•PhantomJS
Realization:
• We don’t need a web server
• We don’t even need a browser
• All we need is the engine, the test file, and the file under test.*

* Drastic simplification – wait for it… ☺
xUnit.js
A Host-Agnostic Test Engine with an
Attribution Based Console Runner
Missed Mandates:
•

•

Organizable:
• Let’s call tests “Facts”, to encourage single aspect-testing
• We’ll group Facts into “Fixtures”, based on “like behavior”
• E.g. several tests exercising a single method
Easy To
Add:
• Want to maintain registration with the test
• C# style attributes are a great [Example] of this behavior
• The syntax is valid javascript, and will be ignored!
Test
Code
[Fixture]

Source Code
function FooClass(){

function foo(){
this.foo=function(){
return “foo”;
};

[Fact]
function ReturnsFoo(){
var expected=“foo”;
}
var actual=new FooClass().foo();
Assert.Equal(expected, actual);
}
}
Successful Run:
Failures, Errors, Script Errors:
[Fixture]
function foo(){
[Fact]
function FailsEqualityAssertion(){
var expected=true;
var actual=false;
Assert.Equal(expected, actual);
}
}

Failure
Failures, Errors, Script Errors:
Failures, Errors, Script Errors:
[Fixture]
function foo(){
[Fact]
function ErrorsOnUnknownMember(){
var expected=true;
var actual={value:true}.slice(0,1);
Assert.Equal(expected, actual);
}
}

Error
Failures, Errors, Script Errors:
Failures, Errors, Script Errors:
[Fixture]
function foo(){
[Fact]
function ThrowsSyntaxErrorOnLoad(){
var expected=if(true));
var actual=false;
Assert.Equal(expected, actual);
}
}

Script Error
Failures, Errors, Script Errors:
Mocks and Stubs:
[Fact]
function MocksWindowReferenceOnHost(){
var expected="expected";
var mockWindow=Mocks.GetMock(Object.Global(), "window", expected);
var actual=null;
mockWindow(function(){
actual=window;
});
Assert.Equal(expected, actual);
}
Mocks and Stubs:
[Fact]
function ReturnsResultWindowHandle(){
var expected="expected";
var windowStub=Stubs.GetObject(
{open:{returnValue:expected}},
{location:"known/url"}
);
var actual=openResults(windowStub);
Assert.Equal(expected, actual);
}

function openResults(
targetWindow
){
var resultsWindow =
targetWindow.open(
"results/url"
);
return resultsWindow;
}
Data-Driven
Tests:Data(1,2,3,4)]
[Fact,
function VerifiesDataIsInRange(data){
var expectedLow = 1;
var expectedHigh = 3;
var actual=data;
Assert.InRange(actual,expectedLow,expectedHigh);
}
Usage:

[…]
Benefits of Use Driven Development:
• Lightweight code host improves development cycle
• No need to wait for browser to manually test most code
• Waste less time understanding emergent side effects
• Maintain confidence while refactoring
• Use unit tests to architect cleaner, more usable APIs
The Big One:
+

xUnit.js =
Challenges:
• Multiple build automation and CI systems
• OS interoperability requirements
• Large browser (javascript engine) support matrix
• Many different teams and modules, with different behaviors
• Existing tests required full system and browser automation
• Selenium tests were becoming increasingly slow and unwieldy
Solutions:
• xUnit.js integrates easily as a command line or processor task
• Out-of-box support for native file I/O strategies and host environments
• Pluggable design allows for simple override and customization patterns
• Custom output strategies allow for report and issue tracker integration
• Shell execution and boundary control obviate end-to-end setup needs
• Selenium tests can be retargeted as integration and smoke tests
Custom Enhancements:
• JSCover Support (http://tntim96.github.io/JSCover/)
• Automatic issue assignment based on changelist author
• Test health history report integration
+

xUnit.js =
Preparation:
• Determine your test matrix
• Build or acquire necessary host engines
• Identify your build system’s executable target structure
• Identify your target test directories and files
Integration:
• Create CI target, .bat file, or .sh script
cscript ./Tools/xUnit.js.Console.js ../../Tests
d8 – ./Tools/xUnit.js.Console.js -- ../../Tests
js ./Tools/xUnit.js.Console.js ../../Tests

• Customize your installation (Optional)
•Attributes (Default file import locations, etc.)
•Output strategies (Reporting, Custom xml formats)
• Integrate additional tools (Optional, but highly recommended)
•JSCover (http://tntim96.github.io/JSCover/)
Happy Coding!
xUnit.js
http://xunitjs.codeplex.com/

John Buchanan
LMTS, salesforce.com, inc.
Introduction to Javascript Unit Testing With xUnit.js

Contenu connexe

Tendances

Fractional Calculus PP
Fractional Calculus PPFractional Calculus PP
Fractional Calculus PP
VRRITC
 
複合システムネットワーク論を読む(公開版)
複合システムネットワーク論を読む(公開版)複合システムネットワーク論を読む(公開版)
複合システムネットワーク論を読む(公開版)
考司 小杉
 
Fractional Calculus
Fractional CalculusFractional Calculus
Fractional Calculus
VRRITC
 
InfoGAN: Interpretable Representation Learning by Information Maximizing Gene...
InfoGAN: Interpretable Representation Learning by Information Maximizing Gene...InfoGAN: Interpretable Representation Learning by Information Maximizing Gene...
InfoGAN: Interpretable Representation Learning by Information Maximizing Gene...
Joonhyung Lee
 

Tendances (20)

Linear vector space
Linear vector spaceLinear vector space
Linear vector space
 
Existence, Uniqueness and Stability Solution of Differential Equations with B...
Existence, Uniqueness and Stability Solution of Differential Equations with B...Existence, Uniqueness and Stability Solution of Differential Equations with B...
Existence, Uniqueness and Stability Solution of Differential Equations with B...
 
Section 9: Equivalence Relations & Cosets
Section 9: Equivalence Relations & CosetsSection 9: Equivalence Relations & Cosets
Section 9: Equivalence Relations & Cosets
 
Soft Actor-Critic Algorithms and Applications 한국어 리뷰
Soft Actor-Critic Algorithms and Applications 한국어 리뷰Soft Actor-Critic Algorithms and Applications 한국어 리뷰
Soft Actor-Critic Algorithms and Applications 한국어 리뷰
 
Depth Fusion from RGB and Depth Sensors II
Depth Fusion from RGB and Depth Sensors IIDepth Fusion from RGB and Depth Sensors II
Depth Fusion from RGB and Depth Sensors II
 
Introduction to Fourier transform and signal analysis
Introduction to Fourier transform and signal analysisIntroduction to Fourier transform and signal analysis
Introduction to Fourier transform and signal analysis
 
01. design & analysis of agorithm intro & complexity analysis
01. design & analysis of agorithm intro & complexity analysis01. design & analysis of agorithm intro & complexity analysis
01. design & analysis of agorithm intro & complexity analysis
 
Fractional Calculus PP
Fractional Calculus PPFractional Calculus PP
Fractional Calculus PP
 
44 randomized-algorithms
44 randomized-algorithms44 randomized-algorithms
44 randomized-algorithms
 
Big omega
Big omegaBig omega
Big omega
 
Fractional calculus and applications
Fractional calculus and applicationsFractional calculus and applications
Fractional calculus and applications
 
複合システムネットワーク論を読む(公開版)
複合システムネットワーク論を読む(公開版)複合システムネットワーク論を読む(公開版)
複合システムネットワーク論を読む(公開版)
 
Fractional Calculus
Fractional CalculusFractional Calculus
Fractional Calculus
 
The time independent Schrödinger wave equation
The time independent Schrödinger wave equationThe time independent Schrödinger wave equation
The time independent Schrödinger wave equation
 
Ft and FFT
Ft and FFTFt and FFT
Ft and FFT
 
20191019 sinkhorn
20191019 sinkhorn20191019 sinkhorn
20191019 sinkhorn
 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
 
InfoGAN: Interpretable Representation Learning by Information Maximizing Gene...
InfoGAN: Interpretable Representation Learning by Information Maximizing Gene...InfoGAN: Interpretable Representation Learning by Information Maximizing Gene...
InfoGAN: Interpretable Representation Learning by Information Maximizing Gene...
 
Interactive emails in Outlook with Adaptive Cards
Interactive emails in Outlook with Adaptive CardsInteractive emails in Outlook with Adaptive Cards
Interactive emails in Outlook with Adaptive Cards
 
Max Flow Problem
Max Flow ProblemMax Flow Problem
Max Flow Problem
 

Similaire à Introduction to Javascript Unit Testing With xUnit.js

Advanced Application Lifecycle Managment
Advanced Application Lifecycle ManagmentAdvanced Application Lifecycle Managment
Advanced Application Lifecycle Managment
Salesforce Developers
 
Sucheta_kale_4.8years_QA
Sucheta_kale_4.8years_QASucheta_kale_4.8years_QA
Sucheta_kale_4.8years_QA
Sucheta Kale
 

Similaire à Introduction to Javascript Unit Testing With xUnit.js (20)

Test Automation With Cucumber JVM, Selenium, and Mocha
Test Automation With Cucumber JVM, Selenium, and MochaTest Automation With Cucumber JVM, Selenium, and Mocha
Test Automation With Cucumber JVM, Selenium, and Mocha
 
Lightning web components - Episode 4 : Security and Testing
Lightning web components  - Episode 4 : Security and TestingLightning web components  - Episode 4 : Security and Testing
Lightning web components - Episode 4 : Security and Testing
 
Self-Service Secure Test and Release Pipelines
Self-Service Secure Test and Release PipelinesSelf-Service Secure Test and Release Pipelines
Self-Service Secure Test and Release Pipelines
 
Advanced Application Lifecycle Managment
Advanced Application Lifecycle ManagmentAdvanced Application Lifecycle Managment
Advanced Application Lifecycle Managment
 
DevOps in Salesforce AppCloud
DevOps in Salesforce AppCloudDevOps in Salesforce AppCloud
DevOps in Salesforce AppCloud
 
Automating the Impossible: End to End Team Development for ISVs (October 14, ...
Automating the Impossible: End to End Team Development for ISVs (October 14, ...Automating the Impossible: End to End Team Development for ISVs (October 14, ...
Automating the Impossible: End to End Team Development for ISVs (October 14, ...
 
Quit Jesting and Test your Lightning Web Components, Phillipe Ozil
Quit Jesting and Test your Lightning Web Components, Phillipe OzilQuit Jesting and Test your Lightning Web Components, Phillipe Ozil
Quit Jesting and Test your Lightning Web Components, Phillipe Ozil
 
Salesforce API Series: Release Management with the Metadata API webinar
Salesforce API Series: Release Management with the Metadata API webinarSalesforce API Series: Release Management with the Metadata API webinar
Salesforce API Series: Release Management with the Metadata API webinar
 
Automating Deployment Between Orgs Using Git & Continuous Integration
Automating Deployment Between Orgs Using Git & Continuous IntegrationAutomating Deployment Between Orgs Using Git & Continuous Integration
Automating Deployment Between Orgs Using Git & Continuous Integration
 
ApexUnit: Open source test framework for apex
ApexUnit: Open source test framework for apexApexUnit: Open source test framework for apex
ApexUnit: Open source test framework for apex
 
Meet The Welkin Suite IDE: Product Overview
Meet The Welkin Suite IDE: Product OverviewMeet The Welkin Suite IDE: Product Overview
Meet The Welkin Suite IDE: Product Overview
 
Sandboxes: The Future of App Development by Evan Barnet & Pam Barnet
Sandboxes: The Future of App Development by Evan Barnet & Pam BarnetSandboxes: The Future of App Development by Evan Barnet & Pam Barnet
Sandboxes: The Future of App Development by Evan Barnet & Pam Barnet
 
Scaling to Millions of Devices and Billions of Events
Scaling to Millions of Devices and Billions of EventsScaling to Millions of Devices and Billions of Events
Scaling to Millions of Devices and Billions of Events
 
Development Best Practices
Development Best PracticesDevelopment Best Practices
Development Best Practices
 
Continuous Integration and Testing with Branch Orgs
Continuous Integration and Testing with Branch OrgsContinuous Integration and Testing with Branch Orgs
Continuous Integration and Testing with Branch Orgs
 
Force.com Friday : Intro to Apex
Force.com Friday : Intro to Apex Force.com Friday : Intro to Apex
Force.com Friday : Intro to Apex
 
Introducing the Welkin Suite IDE for Salesforce
Introducing the Welkin Suite IDE for SalesforceIntroducing the Welkin Suite IDE for Salesforce
Introducing the Welkin Suite IDE for Salesforce
 
San Francisco Jenkins Area Meetup October 2016: Self-service secure test and ...
San Francisco Jenkins Area Meetup October 2016: Self-service secure test and ...San Francisco Jenkins Area Meetup October 2016: Self-service secure test and ...
San Francisco Jenkins Area Meetup October 2016: Self-service secure test and ...
 
JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit Testing
 
Sucheta_kale_4.8years_QA
Sucheta_kale_4.8years_QASucheta_kale_4.8years_QA
Sucheta_kale_4.8years_QA
 

Plus de Salesforce Developers

Plus de Salesforce Developers (20)

Sample Gallery: Reference Code and Best Practices for Salesforce Developers
Sample Gallery: Reference Code and Best Practices for Salesforce DevelopersSample Gallery: Reference Code and Best Practices for Salesforce Developers
Sample Gallery: Reference Code and Best Practices for Salesforce Developers
 
Maximizing Salesforce Lightning Experience and Lightning Component Performance
Maximizing Salesforce Lightning Experience and Lightning Component PerformanceMaximizing Salesforce Lightning Experience and Lightning Component Performance
Maximizing Salesforce Lightning Experience and Lightning Component Performance
 
Local development with Open Source Base Components
Local development with Open Source Base ComponentsLocal development with Open Source Base Components
Local development with Open Source Base Components
 
TrailheaDX India : Developer Highlights
TrailheaDX India : Developer HighlightsTrailheaDX India : Developer Highlights
TrailheaDX India : Developer Highlights
 
Why developers shouldn’t miss TrailheaDX India
Why developers shouldn’t miss TrailheaDX IndiaWhy developers shouldn’t miss TrailheaDX India
Why developers shouldn’t miss TrailheaDX India
 
CodeLive: Build Lightning Web Components faster with Local Development
CodeLive: Build Lightning Web Components faster with Local DevelopmentCodeLive: Build Lightning Web Components faster with Local Development
CodeLive: Build Lightning Web Components faster with Local Development
 
CodeLive: Converting Aura Components to Lightning Web Components
CodeLive: Converting Aura Components to Lightning Web ComponentsCodeLive: Converting Aura Components to Lightning Web Components
CodeLive: Converting Aura Components to Lightning Web Components
 
Enterprise-grade UI with open source Lightning Web Components
Enterprise-grade UI with open source Lightning Web ComponentsEnterprise-grade UI with open source Lightning Web Components
Enterprise-grade UI with open source Lightning Web Components
 
TrailheaDX and Summer '19: Developer Highlights
TrailheaDX and Summer '19: Developer HighlightsTrailheaDX and Summer '19: Developer Highlights
TrailheaDX and Summer '19: Developer Highlights
 
Live coding with LWC
Live coding with LWCLive coding with LWC
Live coding with LWC
 
LWC Episode 3- Component Communication and Aura Interoperability
LWC Episode 3- Component Communication and Aura InteroperabilityLWC Episode 3- Component Communication and Aura Interoperability
LWC Episode 3- Component Communication and Aura Interoperability
 
Lightning web components episode 2- work with salesforce data
Lightning web components   episode 2- work with salesforce dataLightning web components   episode 2- work with salesforce data
Lightning web components episode 2- work with salesforce data
 
Lightning web components - Episode 1 - An Introduction
Lightning web components - Episode 1 - An IntroductionLightning web components - Episode 1 - An Introduction
Lightning web components - Episode 1 - An Introduction
 
Migrating CPQ to Advanced Calculator and JSQCP
Migrating CPQ to Advanced Calculator and JSQCPMigrating CPQ to Advanced Calculator and JSQCP
Migrating CPQ to Advanced Calculator and JSQCP
 
Scale with Large Data Volumes and Big Objects in Salesforce
Scale with Large Data Volumes and Big Objects in SalesforceScale with Large Data Volumes and Big Objects in Salesforce
Scale with Large Data Volumes and Big Objects in Salesforce
 
Replicate Salesforce Data in Real Time with Change Data Capture
Replicate Salesforce Data in Real Time with Change Data CaptureReplicate Salesforce Data in Real Time with Change Data Capture
Replicate Salesforce Data in Real Time with Change Data Capture
 
Modern Development with Salesforce DX
Modern Development with Salesforce DXModern Development with Salesforce DX
Modern Development with Salesforce DX
 
Get Into Lightning Flow Development
Get Into Lightning Flow DevelopmentGet Into Lightning Flow Development
Get Into Lightning Flow Development
 
Integrate CMS Content Into Lightning Communities with CMS Connect
Integrate CMS Content Into Lightning Communities with CMS ConnectIntegrate CMS Content Into Lightning Communities with CMS Connect
Integrate CMS Content Into Lightning Communities with CMS Connect
 
Introduction to MuleSoft
Introduction to MuleSoftIntroduction to MuleSoft
Introduction to MuleSoft
 

Dernier

Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
FIDO Alliance
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
FIDO Alliance
 

Dernier (20)

Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptx
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 

Introduction to Javascript Unit Testing With xUnit.js

  • 1. Javascript Unit Testing with xUnit.js Building cleaner APIs, faster! John Buchanan, salesforce.com, inc. Lead Member of Technical Staff
  • 2. Safe harbor Safe harbor statement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services. The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of any litigation, risks associated with completed and any possible mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most recent fiscal quarter. These documents and others containing important disclosures are available on the SEC Filings section of the Investor Information section of our Web site. Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
  • 3. Challenges: 1. What are some of the problems with testing javascript?
  • 4. Challenges: 1. What are some of the problems with testing javascript? • Boundary Control (Web requests, DOM access)
  • 5. Challenges: 1. What are some of the problems with testing javascript? • Boundary Control (Web requests, DOM access) • Automation / Continuous Integration
  • 6. Challenges: 1. What are some of the problems with testing javascript? • Boundary Control (Web requests, DOM access) • Automation / Continuous Integration • Design Dependencies, Encapsulation
  • 7. Challenges: 2. What are the differences between unit and integration tests?
  • 8. Challenges: 2. What are the differences between unit and integration tests? • Single module or component vs. interactions between modules
  • 9. Challenges: 2. What are the differences between unit and integration tests? • Single module or component vs. interactions between modules • Boundary Control (Web requests, DOM access)
  • 10. Challenges: 2. What are the differences between unit and integration tests? • Single module or component vs. interactions between modules • Boundary Control (Web requests, DOM access) • Cost to exercise in automation: Unit tests are cheap
  • 11. Challenges: 2. What are the differences between unit and integration tests? • Single module or component vs. interactions between modules • Boundary Control (Web requests, DOM access) • Cost to exercise in automation: Unit tests are cheap • Dependencies are abstracted in units, included in integrations
  • 14. xUnit.js A Host-Agnostic Test Engine with an Attribution Based Console Runner
  • 16. A brief history of xUnit.js
  • 17. xUnit.js: • Started in 2006, open source project hosted on CodePlex • Frustrated with typical test registration systems • Environmental requirements were expensive (Server, browser) • Loved the simplicity and speed of the WSH (cscript.exe) • Starting to understand using unit tests as a design tool
  • 18. Unit Tests: • Should be easily organizable • Must to be simple to add, minimizing “dev bounce” • Need to be easy to run, but also run fast • Should help enforce dependency isolation • Could allow for custom types of decoration (Ignore, Test Category, etc.)
  • 19. Host Agnostic: • Should support common hosts out of the box: •Google Chrome (V8) •Mozilla Firefox (SpiderMonkey) •Microsoft Internet Explorer 4-11 (JScript and Chakra, via cscript.exe) •Mozilla Rhino • Must also be able to easily add new and special use hosts: •JSDB •NodeJS •PhantomJS
  • 20. Realization: • We don’t need a web server • We don’t even need a browser • All we need is the engine, the test file, and the file under test.* * Drastic simplification – wait for it… ☺
  • 21. xUnit.js A Host-Agnostic Test Engine with an Attribution Based Console Runner
  • 22. Missed Mandates: • • Organizable: • Let’s call tests “Facts”, to encourage single aspect-testing • We’ll group Facts into “Fixtures”, based on “like behavior” • E.g. several tests exercising a single method Easy To Add: • Want to maintain registration with the test • C# style attributes are a great [Example] of this behavior • The syntax is valid javascript, and will be ignored!
  • 23. Test Code [Fixture] Source Code function FooClass(){ function foo(){ this.foo=function(){ return “foo”; }; [Fact] function ReturnsFoo(){ var expected=“foo”; } var actual=new FooClass().foo(); Assert.Equal(expected, actual); } }
  • 25. Failures, Errors, Script Errors: [Fixture] function foo(){ [Fact] function FailsEqualityAssertion(){ var expected=true; var actual=false; Assert.Equal(expected, actual); } } Failure
  • 27. Failures, Errors, Script Errors: [Fixture] function foo(){ [Fact] function ErrorsOnUnknownMember(){ var expected=true; var actual={value:true}.slice(0,1); Assert.Equal(expected, actual); } } Error
  • 29. Failures, Errors, Script Errors: [Fixture] function foo(){ [Fact] function ThrowsSyntaxErrorOnLoad(){ var expected=if(true)); var actual=false; Assert.Equal(expected, actual); } } Script Error
  • 31. Mocks and Stubs: [Fact] function MocksWindowReferenceOnHost(){ var expected="expected"; var mockWindow=Mocks.GetMock(Object.Global(), "window", expected); var actual=null; mockWindow(function(){ actual=window; }); Assert.Equal(expected, actual); }
  • 32. Mocks and Stubs: [Fact] function ReturnsResultWindowHandle(){ var expected="expected"; var windowStub=Stubs.GetObject( {open:{returnValue:expected}}, {location:"known/url"} ); var actual=openResults(windowStub); Assert.Equal(expected, actual); } function openResults( targetWindow ){ var resultsWindow = targetWindow.open( "results/url" ); return resultsWindow; }
  • 33. Data-Driven Tests:Data(1,2,3,4)] [Fact, function VerifiesDataIsInRange(data){ var expectedLow = 1; var expectedHigh = 3; var actual=data; Assert.InRange(actual,expectedLow,expectedHigh); }
  • 35. Benefits of Use Driven Development: • Lightweight code host improves development cycle • No need to wait for browser to manually test most code • Waste less time understanding emergent side effects • Maintain confidence while refactoring • Use unit tests to architect cleaner, more usable APIs The Big One:
  • 37. Challenges: • Multiple build automation and CI systems • OS interoperability requirements • Large browser (javascript engine) support matrix • Many different teams and modules, with different behaviors • Existing tests required full system and browser automation • Selenium tests were becoming increasingly slow and unwieldy
  • 38. Solutions: • xUnit.js integrates easily as a command line or processor task • Out-of-box support for native file I/O strategies and host environments • Pluggable design allows for simple override and customization patterns • Custom output strategies allow for report and issue tracker integration • Shell execution and boundary control obviate end-to-end setup needs • Selenium tests can be retargeted as integration and smoke tests
  • 39. Custom Enhancements: • JSCover Support (http://tntim96.github.io/JSCover/) • Automatic issue assignment based on changelist author • Test health history report integration
  • 41. Preparation: • Determine your test matrix • Build or acquire necessary host engines • Identify your build system’s executable target structure • Identify your target test directories and files
  • 42. Integration: • Create CI target, .bat file, or .sh script cscript ./Tools/xUnit.js.Console.js ../../Tests d8 – ./Tools/xUnit.js.Console.js -- ../../Tests js ./Tools/xUnit.js.Console.js ../../Tests • Customize your installation (Optional) •Attributes (Default file import locations, etc.) •Output strategies (Reporting, Custom xml formats) • Integrate additional tools (Optional, but highly recommended) •JSCover (http://tntim96.github.io/JSCover/)