SlideShare a Scribd company logo
1 of 26
DANIEL JIMENEZ GARCIA
UNIT
TESTING
TYPESCRIPT
Daniel Jimenez | 2015-11-01 | Page 2
uSING…
› Qunit (Test Framework)
– Alternatives: Jasmine (BDD) Mocha (Node.js)
› Sinon (Mocking Framework)
– Alternative: Jasmine spies
› Grunt (JS Task Runner)
– Alternative: Gulp
Daniel Jimenez | 2015-11-01 | Page 3
1. Introduction
2. Writing Typescript tests using QUnit
and Sinon.js
› Writing Qunit tests
› Basic mocking
› Mocking with Sinon.js
› Advanced tips
3. Unit testing workflows
› Manual workflow
› Automated workflow using grunt
› Scaffold html runner files using grunt
› External modules
Agenda
1. INTRODUCTION
Daniel Jimenez | 2015-11-01 | Page 5
Qunit basics (1)
Visit: http://qunitjs.com/
Qunit requires the following pieces
Transform
The production code
One or more JavaScript files
Code to be tested
Defines the tests
The tests to be run
Usually one JavaScript file
Runs the tests
A test runner
HTML file. References QUnit library, production code
and test code
Test runner
Prod code
Test code
Daniel Jimenez | 2015-11-01 | Page 6
› Running a test requires a browser
– Open HTML file in browser that includes:
› QUnit JS file
› QUnit CSS file
› Production JS files
› Test JS files
– Results are displayed in the html page
› Reload or click rerun after changes
› A JS task runner like Grunt can run
the tests without a browser
Qunit basics (2)
Daniel Jimenez | 2015-11-01 | Page 7
› When testing TypeScript
– Compile TypeScript code into JavaScript
– Reference compiled JavaScript in the
HTML runner file
– Use a declaration file to reference libraries
like QUnit in your test TypeScript code
› Download .d.ts files from:
http://definitelytyped.org/
› A JS task runner like Grunt can be
used to compile TS code.
› Some editors and IDE (like VS) can
also compile the TS code.
Qunit basics (3)
Daniel Jimenez | 2015-11-01 | Page 8
DEMO: QUNIT BASICS
2. WRITING Typescript
tests using QUnit and
Sinon.js
Daniel Jimenez | 2015-11-01 | Page 10
Writing qunit tests (1)
• Reference declarations
for Qunit, Sinon, etc
• Reference source code
• Import libraries in html
• Create test module
• Allows common setup
and teardown
• Add tests to the module
using QUnit test function
• Test logic goes in the
inline function
Daniel Jimenez | 2015-11-01 | Page 11
Writing qunit tests (2)
• Use module setup and teardown
• Create common dependencies and data in setup.
• Perform any cleanup between tests in teardown.
• Use appropriated QUnit assertions to your test.
• Avoid overusing ok assertion
• Don’t use equal when you need deepEqual
Familiarize with the range of assertions:
http://api.qunitjs.com/category/assert/
Daniel Jimenez | 2015-11-01 | Page 12
› Take advantage of structural typing
– Structural typing is a way of relating types
based solely on their members
› Need a stub of a class or interface?
– Create empty object literal
– Cast it as the class/interface
› Need a mock of a class or interface?
– Create an object literal with just the
members needed
– Cast it as the class/interface
› You can cast as any but you will lose
compiler support.
BASIC MOCKING (1)
Daniel Jimenez | 2015-11-01 | Page 13
› Any object or member can be mocked
– Mock method in existing object
– Mock getter in singleton without setter
› Be careful if changing prototypes
– At least restore them
› Try to avoid accessing private
members
– Anything accessible with the brackets
notation can be mocked
– This includes TS private members
› Use this with hard to test code. Then
refactor your code and your tests
BASIC MOCKING (2)
Daniel Jimenez | 2015-11-01 | Page 14
› Create spies to verify interactions
– Let you assert when a particular method
was called, how many times, with which
arguments, etc
– Can wrap an existing method, but the
method will still be called
– If you need to control what the method will
return, use a stub
› http://sinonjs.org/docs/#spies
MOCKING WITH SINON (1)
Daniel Jimenez | 2015-11-01 | Page 15
› Create stubs to replace method
implementations with mocked ones
– Existing methods are replaced, the
original implementation is not executed
– Let you specify the return values of a
particular method.
– Allows complex setup like:
› a return value for the Nth call
› a return value for specific arguments
› Stubs are also spies
– When possible choose spies over stubs
› http://sinonjs.org/docs/#stubs
MOCKING WITH SINON (2)
Daniel Jimenez | 2015-11-01 | Page 16
Advanced tips (1)
• Create a sinon sandbox in test setup
• Sinon stubs/spies in test setup are created using
the sandbox
• Restore the sandbox in test teardown
• Move common test references and type
definitions to its own file.
• Reference this file in your test files
Daniel Jimenez | 2015-11-01 | Page 17
Advanced tips (2)
• Try to avoid QUnit asynchronous tests!
• Use stubs to return resolved/rejected promises
• Use a spy to verify done/fail callbacks
• Avoid time-dependent tests!
• Use sinon FakeTimers to control Date, setInterval
and setTimeout
• Use a sandbox to restore the clock between tests
Daniel Jimenez | 2015-11-01 | Page 18
Advanced tips (3)
• Use object builder pattern with fluent syntax
• Useful not only when creating test data but also
creating classes under test
• Test will support refactorings better
• Use sinon matchers and assertions
• Test code is more expressive
• Avoid checking more than is needed
Daniel Jimenez | 2015-11-01 | Page 19
DEMO: writing tests using
QUNIT and sinon
3. Unit testing
workflows
Daniel Jimenez | 2015-11-01 | Page 21
MANUAL WORKFLOW
You can run unit tests just by compiling typescript and using a browser
Might be enough for small projects
Create tests
Write TypeScript tests
Create QUnit html test
runners
Manually manage
dependencies by adding
scripts in the test runner
html file
Manually manage paths to
the compiled files
Compile TS
Compile TypeScript code
and tests into JavaScript.
Some IDE and editors can
compile TypeScript
automatically
You can also
manually compile using
tsc.exe or Node.js
Run in browser
Manually open QUnit test
runner html files in the browser
Every html file has to be
opened independently
Requires someone
to run the tests and
interpret the results
Daniel Jimenez | 2015-11-01 | Page 22
AUTOMATing the WORKFLOW USING
Grunt is a JS Task Runner that can automate tasks like bundling or minification
There are hundreds of plugins, including TS compilation and running QUnit tests
STEP 4
Text
Create tests
Write TypeScript tests
Create QUnit html test
runners
Manually manage
dependencies by adding
scripts in the test runner
html file
Manually manage paths to
the compiled files in the
folder
Configure Grunt
Install grunt-ts for compiling
TypeScript
Install grunt-contrib-qunit
for running QUnit tests
Add tasks in your
gruntfile for:
1. Clean a temp folder
2. Compile into temp
folder
3. Copy html files into
temp folder
4. Run QUnit tests
Run Grunt
Add a “test” task in the
gruntfile . It will run the
tasks in the full process
Run grunt either from the
command line (installing
grunt-cli) or from an
IDE like Visual Studio
The full process can be run
with a single command, will
report test results and the
exit code will be non zero if
failed
http://gruntjs.com/
https://github.com/grunt
js/grunt-contrib-qunit
https://github.com/Type
Strong/grunt-ts
Daniel Jimenez | 2015-11-01 | Page 23
SCAFFOLD QUNIT HTML FILES USING
You can create your own grunt plugins and tasks
Create a task that searches for ///< reference tags and scaffolds the html file
STEP 4
Text
Create tests
Write TypeScript tests
Configure Grunt
Create task to scaffold
QUnit html files
Update the tasks in your
grunt file as :
1. Clean temp folder
2. Compile into temp
folder
3. Scaffold html files into
temp folder
4. Run QUnit tests
Run Grunt
Add a “test” task in the
gruntfile . It will run the
tasks in the full process
Run grunt either from the
command line (installing
grunt-cli) or from an
IDE like Visual Studio
The full process can be run
with a single command, will
report test results and the
exit code will be non zero if
failed
Check example in:
https://github.com/DaniJG
/TypeScriptUTWorkflows
Daniel Jimenez | 2015-11-01 | Page 24
USING EXTERNAL MODULES WITH
• Write TypeScript code using external modules via
export and import (including your tests)
• Specify the module option when compiling
TypeScript
• Dependencies are loaded by the module system
(require.js or common.js) instead of script tags.
• Using require.js needs to adjust test startup
Daniel Jimenez | 2015-11-01 | Page 25
DEMO: unit testing workflows
Unit Testing TypeScript

More Related Content

What's hot

Test Driven Development with OSGi - Balázs Zsoldos
Test Driven Development with OSGi - Balázs ZsoldosTest Driven Development with OSGi - Balázs Zsoldos
Test Driven Development with OSGi - Balázs Zsoldosmfrancis
 
Working with c++ legacy code
Working with c++ legacy codeWorking with c++ legacy code
Working with c++ legacy codeDror Helper
 
ATO 2014 - So You Think You Know 'Go'? The Go Programming Language
ATO 2014 - So You Think You Know 'Go'? The Go Programming LanguageATO 2014 - So You Think You Know 'Go'? The Go Programming Language
ATO 2014 - So You Think You Know 'Go'? The Go Programming LanguageJohn Potocny
 
Flash Camp Chennai - Build automation of Flex and AIR applications
Flash Camp Chennai - Build automation of Flex and AIR applicationsFlash Camp Chennai - Build automation of Flex and AIR applications
Flash Camp Chennai - Build automation of Flex and AIR applicationsRIA RUI Society
 
Develop Maintainable Apps - edUiConf
Develop Maintainable Apps - edUiConfDevelop Maintainable Apps - edUiConf
Develop Maintainable Apps - edUiConfAnnyce Davis
 
The New York Times: Sustainable Systems, Powered by Python
The New York Times: Sustainable Systems, Powered by PythonThe New York Times: Sustainable Systems, Powered by Python
The New York Times: Sustainable Systems, Powered by PythonAll Things Open
 
Developer Job in Practice
Developer Job in PracticeDeveloper Job in Practice
Developer Job in Practiceintive
 
Vagrant and Docker
Vagrant and DockerVagrant and Docker
Vagrant and DockerNascenia IT
 
TDD for joomla extensions
TDD for joomla extensionsTDD for joomla extensions
TDD for joomla extensionsRoberto Segura
 
DockerCon US 2016 - Scaling Open Source operations
DockerCon US 2016 - Scaling Open Source operationsDockerCon US 2016 - Scaling Open Source operations
DockerCon US 2016 - Scaling Open Source operationsArnaud Porterie
 
Test Driven Development with PHP
Test Driven Development with PHPTest Driven Development with PHP
Test Driven Development with PHPRogério Vicente
 
Advantages and disadvantages of a monorepo
Advantages and disadvantages of a monorepoAdvantages and disadvantages of a monorepo
Advantages and disadvantages of a monorepoIanDavidson56
 
Devops is (not ) a buzzword
Devops is (not ) a buzzwordDevops is (not ) a buzzword
Devops is (not ) a buzzwordMiguel Fonseca
 
Intro to Continuous Integration
Intro to Continuous IntegrationIntro to Continuous Integration
Intro to Continuous IntegrationTal Mor (Moshayov)
 
Testing cloud and kubernetes applications - ElasTest
Testing cloud and kubernetes applications - ElasTestTesting cloud and kubernetes applications - ElasTest
Testing cloud and kubernetes applications - ElasTestMicael Gallego
 

What's hot (20)

Test Driven Development with OSGi - Balázs Zsoldos
Test Driven Development with OSGi - Balázs ZsoldosTest Driven Development with OSGi - Balázs Zsoldos
Test Driven Development with OSGi - Balázs Zsoldos
 
Working with c++ legacy code
Working with c++ legacy codeWorking with c++ legacy code
Working with c++ legacy code
 
ATO 2014 - So You Think You Know 'Go'? The Go Programming Language
ATO 2014 - So You Think You Know 'Go'? The Go Programming LanguageATO 2014 - So You Think You Know 'Go'? The Go Programming Language
ATO 2014 - So You Think You Know 'Go'? The Go Programming Language
 
Flash Camp Chennai - Build automation of Flex and AIR applications
Flash Camp Chennai - Build automation of Flex and AIR applicationsFlash Camp Chennai - Build automation of Flex and AIR applications
Flash Camp Chennai - Build automation of Flex and AIR applications
 
Develop Maintainable Apps - edUiConf
Develop Maintainable Apps - edUiConfDevelop Maintainable Apps - edUiConf
Develop Maintainable Apps - edUiConf
 
Go lang
Go langGo lang
Go lang
 
The New York Times: Sustainable Systems, Powered by Python
The New York Times: Sustainable Systems, Powered by PythonThe New York Times: Sustainable Systems, Powered by Python
The New York Times: Sustainable Systems, Powered by Python
 
Developer Job in Practice
Developer Job in PracticeDeveloper Job in Practice
Developer Job in Practice
 
Vagrant and Docker
Vagrant and DockerVagrant and Docker
Vagrant and Docker
 
TDD for joomla extensions
TDD for joomla extensionsTDD for joomla extensions
TDD for joomla extensions
 
Monorepo at Pinterest
Monorepo at PinterestMonorepo at Pinterest
Monorepo at Pinterest
 
XPDays-2018
XPDays-2018XPDays-2018
XPDays-2018
 
DockerCon US 2016 - Scaling Open Source operations
DockerCon US 2016 - Scaling Open Source operationsDockerCon US 2016 - Scaling Open Source operations
DockerCon US 2016 - Scaling Open Source operations
 
Test Driven Development with PHP
Test Driven Development with PHPTest Driven Development with PHP
Test Driven Development with PHP
 
Advantages and disadvantages of a monorepo
Advantages and disadvantages of a monorepoAdvantages and disadvantages of a monorepo
Advantages and disadvantages of a monorepo
 
Devops is (not ) a buzzword
Devops is (not ) a buzzwordDevops is (not ) a buzzword
Devops is (not ) a buzzword
 
Mono Repo
Mono RepoMono Repo
Mono Repo
 
Intro to Continuous Integration
Intro to Continuous IntegrationIntro to Continuous Integration
Intro to Continuous Integration
 
Testing cloud and kubernetes applications - ElasTest
Testing cloud and kubernetes applications - ElasTestTesting cloud and kubernetes applications - ElasTest
Testing cloud and kubernetes applications - ElasTest
 
The way Devs do Ops
The way Devs do OpsThe way Devs do Ops
The way Devs do Ops
 

Viewers also liked

13 Signs You Might Be A Bad Boss
13 Signs You Might Be A Bad Boss13 Signs You Might Be A Bad Boss
13 Signs You Might Be A Bad BossOfficevibe
 
#SUGDE Sitecore Gesundheit
#SUGDE Sitecore Gesundheit #SUGDE Sitecore Gesundheit
#SUGDE Sitecore Gesundheit chriswoj
 
Javascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and SinonJavascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and SinonLars Thorup
 
Testing with Express, Mocha & Chai
Testing with Express, Mocha & ChaiTesting with Express, Mocha & Chai
Testing with Express, Mocha & ChaiJoerg Henning
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoveragemlilley
 
Testing Javascript Apps with Mocha and Chai
Testing Javascript Apps with Mocha and ChaiTesting Javascript Apps with Mocha and Chai
Testing Javascript Apps with Mocha and ChaiAndrew Winder
 
Test automation introduction training at Polteq
Test automation   introduction training at PolteqTest automation   introduction training at Polteq
Test automation introduction training at PolteqMartijn de Vrieze
 
Unit testing with mocha
Unit testing with mochaUnit testing with mocha
Unit testing with mochaRevath S Kumar
 
Finjs - Angular 2 better faster stronger
Finjs - Angular 2 better faster strongerFinjs - Angular 2 better faster stronger
Finjs - Angular 2 better faster strongerChristoffer Noring
 
Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Hazem Saleh
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingLars Thorup
 
SoapUI one key to all doors
SoapUI one key to all doorsSoapUI one key to all doors
SoapUI one key to all doorsYegor Maksymchuk
 
Test trend analysis: Towards robust reliable and timely tests
Test trend analysis: Towards robust reliable and timely testsTest trend analysis: Towards robust reliable and timely tests
Test trend analysis: Towards robust reliable and timely testsHugh McCamphill
 
WixAutomation - Test State Pattern - Selenium Camp 2017
WixAutomation - Test State Pattern - Selenium Camp 2017WixAutomation - Test State Pattern - Selenium Camp 2017
WixAutomation - Test State Pattern - Selenium Camp 2017Roi Ashkenazi
 
How does Java 8 exert hidden power on Test Automation?
How does Java 8 exert hidden power on Test Automation?How does Java 8 exert hidden power on Test Automation?
How does Java 8 exert hidden power on Test Automation?Sergey Korol
 
The wild wild west of Selenium Capabilities
The wild wild west of Selenium CapabilitiesThe wild wild west of Selenium Capabilities
The wild wild west of Selenium CapabilitiesAdi Ofri
 
Roman iovlev. Test UI with JDI - Selenium camp
Roman iovlev. Test UI with JDI - Selenium campRoman iovlev. Test UI with JDI - Selenium camp
Roman iovlev. Test UI with JDI - Selenium campРоман Иовлев
 
Colorful world-of-visual-automation-testing-latest
Colorful world-of-visual-automation-testing-latestColorful world-of-visual-automation-testing-latest
Colorful world-of-visual-automation-testing-latestOnur Baskirt
 

Viewers also liked (20)

13 Signs You Might Be A Bad Boss
13 Signs You Might Be A Bad Boss13 Signs You Might Be A Bad Boss
13 Signs You Might Be A Bad Boss
 
Unit testing js
Unit testing jsUnit testing js
Unit testing js
 
Q unit
Q unitQ unit
Q unit
 
#SUGDE Sitecore Gesundheit
#SUGDE Sitecore Gesundheit #SUGDE Sitecore Gesundheit
#SUGDE Sitecore Gesundheit
 
Javascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and SinonJavascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and Sinon
 
Testing with Express, Mocha & Chai
Testing with Express, Mocha & ChaiTesting with Express, Mocha & Chai
Testing with Express, Mocha & Chai
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
 
Testing Javascript Apps with Mocha and Chai
Testing Javascript Apps with Mocha and ChaiTesting Javascript Apps with Mocha and Chai
Testing Javascript Apps with Mocha and Chai
 
Test automation introduction training at Polteq
Test automation   introduction training at PolteqTest automation   introduction training at Polteq
Test automation introduction training at Polteq
 
Unit testing with mocha
Unit testing with mochaUnit testing with mocha
Unit testing with mocha
 
Finjs - Angular 2 better faster stronger
Finjs - Angular 2 better faster strongerFinjs - Angular 2 better faster stronger
Finjs - Angular 2 better faster stronger
 
Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
 
SoapUI one key to all doors
SoapUI one key to all doorsSoapUI one key to all doors
SoapUI one key to all doors
 
Test trend analysis: Towards robust reliable and timely tests
Test trend analysis: Towards robust reliable and timely testsTest trend analysis: Towards robust reliable and timely tests
Test trend analysis: Towards robust reliable and timely tests
 
WixAutomation - Test State Pattern - Selenium Camp 2017
WixAutomation - Test State Pattern - Selenium Camp 2017WixAutomation - Test State Pattern - Selenium Camp 2017
WixAutomation - Test State Pattern - Selenium Camp 2017
 
How does Java 8 exert hidden power on Test Automation?
How does Java 8 exert hidden power on Test Automation?How does Java 8 exert hidden power on Test Automation?
How does Java 8 exert hidden power on Test Automation?
 
The wild wild west of Selenium Capabilities
The wild wild west of Selenium CapabilitiesThe wild wild west of Selenium Capabilities
The wild wild west of Selenium Capabilities
 
Roman iovlev. Test UI with JDI - Selenium camp
Roman iovlev. Test UI with JDI - Selenium campRoman iovlev. Test UI with JDI - Selenium camp
Roman iovlev. Test UI with JDI - Selenium camp
 
Colorful world-of-visual-automation-testing-latest
Colorful world-of-visual-automation-testing-latestColorful world-of-visual-automation-testing-latest
Colorful world-of-visual-automation-testing-latest
 

Similar to Unit Testing TypeScript

Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBaskar K
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)Thierry Gayet
 
3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API - 3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API - Ortus Solutions, Corp
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION APIGavin Pickin
 
Test all the things! Automated testing with Drupal 8
Test all the things! Automated testing with Drupal 8Test all the things! Automated testing with Drupal 8
Test all the things! Automated testing with Drupal 8Sam Becker
 
Survival of the Continuist
Survival of the ContinuistSurvival of the Continuist
Survival of the ContinuistPaul Blundell
 
Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMSJustinHolt20
 
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017Ortus Solutions, Corp
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql ServerDavid P. Moore
 
Unit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUGUnit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUGegoodwintx
 
Docker–Grid (A On demand and Scalable dockerized selenium grid architecture)
Docker–Grid (A On demand and Scalable dockerized selenium grid architecture)Docker–Grid (A On demand and Scalable dockerized selenium grid architecture)
Docker–Grid (A On demand and Scalable dockerized selenium grid architecture)STePINForum
 
Developers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonDevelopers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonIneke Scheffers
 
Agile Engineering Sparker GLASScon 2015
Agile Engineering Sparker GLASScon 2015Agile Engineering Sparker GLASScon 2015
Agile Engineering Sparker GLASScon 2015Stephen Ritchie
 
Test Driven Development & CI/CD
Test Driven Development & CI/CDTest Driven Development & CI/CD
Test Driven Development & CI/CDShanmuga S Muthu
 
Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019Grzegorz Miejski
 

Similar to Unit Testing TypeScript (20)

Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NET
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)
 
3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API - 3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API -
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API
 
Unit testing (eng)
Unit testing (eng)Unit testing (eng)
Unit testing (eng)
 
Test all the things! Automated testing with Drupal 8
Test all the things! Automated testing with Drupal 8Test all the things! Automated testing with Drupal 8
Test all the things! Automated testing with Drupal 8
 
Survival of the Continuist
Survival of the ContinuistSurvival of the Continuist
Survival of the Continuist
 
Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMS
 
Automatic Test 2019-07-25
Automatic Test 2019-07-25Automatic Test 2019-07-25
Automatic Test 2019-07-25
 
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
 
Unit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUGUnit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUG
 
Docker–Grid (A On demand and Scalable dockerized selenium grid architecture)
Docker–Grid (A On demand and Scalable dockerized selenium grid architecture)Docker–Grid (A On demand and Scalable dockerized selenium grid architecture)
Docker–Grid (A On demand and Scalable dockerized selenium grid architecture)
 
AWS Code Services
AWS Code ServicesAWS Code Services
AWS Code Services
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Jenkins presentation
Jenkins presentationJenkins presentation
Jenkins presentation
 
Developers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonDevelopers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomon
 
Agile Engineering Sparker GLASScon 2015
Agile Engineering Sparker GLASScon 2015Agile Engineering Sparker GLASScon 2015
Agile Engineering Sparker GLASScon 2015
 
Test Driven Development & CI/CD
Test Driven Development & CI/CDTest Driven Development & CI/CD
Test Driven Development & CI/CD
 
Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019
 

Recently uploaded

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
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
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
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
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 

Recently uploaded (20)

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
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...
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
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
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 

Unit Testing TypeScript

  • 2. Daniel Jimenez | 2015-11-01 | Page 2 uSING… › Qunit (Test Framework) – Alternatives: Jasmine (BDD) Mocha (Node.js) › Sinon (Mocking Framework) – Alternative: Jasmine spies › Grunt (JS Task Runner) – Alternative: Gulp
  • 3. Daniel Jimenez | 2015-11-01 | Page 3 1. Introduction 2. Writing Typescript tests using QUnit and Sinon.js › Writing Qunit tests › Basic mocking › Mocking with Sinon.js › Advanced tips 3. Unit testing workflows › Manual workflow › Automated workflow using grunt › Scaffold html runner files using grunt › External modules Agenda
  • 5. Daniel Jimenez | 2015-11-01 | Page 5 Qunit basics (1) Visit: http://qunitjs.com/ Qunit requires the following pieces Transform The production code One or more JavaScript files Code to be tested Defines the tests The tests to be run Usually one JavaScript file Runs the tests A test runner HTML file. References QUnit library, production code and test code Test runner Prod code Test code
  • 6. Daniel Jimenez | 2015-11-01 | Page 6 › Running a test requires a browser – Open HTML file in browser that includes: › QUnit JS file › QUnit CSS file › Production JS files › Test JS files – Results are displayed in the html page › Reload or click rerun after changes › A JS task runner like Grunt can run the tests without a browser Qunit basics (2)
  • 7. Daniel Jimenez | 2015-11-01 | Page 7 › When testing TypeScript – Compile TypeScript code into JavaScript – Reference compiled JavaScript in the HTML runner file – Use a declaration file to reference libraries like QUnit in your test TypeScript code › Download .d.ts files from: http://definitelytyped.org/ › A JS task runner like Grunt can be used to compile TS code. › Some editors and IDE (like VS) can also compile the TS code. Qunit basics (3)
  • 8. Daniel Jimenez | 2015-11-01 | Page 8 DEMO: QUNIT BASICS
  • 9. 2. WRITING Typescript tests using QUnit and Sinon.js
  • 10. Daniel Jimenez | 2015-11-01 | Page 10 Writing qunit tests (1) • Reference declarations for Qunit, Sinon, etc • Reference source code • Import libraries in html • Create test module • Allows common setup and teardown • Add tests to the module using QUnit test function • Test logic goes in the inline function
  • 11. Daniel Jimenez | 2015-11-01 | Page 11 Writing qunit tests (2) • Use module setup and teardown • Create common dependencies and data in setup. • Perform any cleanup between tests in teardown. • Use appropriated QUnit assertions to your test. • Avoid overusing ok assertion • Don’t use equal when you need deepEqual Familiarize with the range of assertions: http://api.qunitjs.com/category/assert/
  • 12. Daniel Jimenez | 2015-11-01 | Page 12 › Take advantage of structural typing – Structural typing is a way of relating types based solely on their members › Need a stub of a class or interface? – Create empty object literal – Cast it as the class/interface › Need a mock of a class or interface? – Create an object literal with just the members needed – Cast it as the class/interface › You can cast as any but you will lose compiler support. BASIC MOCKING (1)
  • 13. Daniel Jimenez | 2015-11-01 | Page 13 › Any object or member can be mocked – Mock method in existing object – Mock getter in singleton without setter › Be careful if changing prototypes – At least restore them › Try to avoid accessing private members – Anything accessible with the brackets notation can be mocked – This includes TS private members › Use this with hard to test code. Then refactor your code and your tests BASIC MOCKING (2)
  • 14. Daniel Jimenez | 2015-11-01 | Page 14 › Create spies to verify interactions – Let you assert when a particular method was called, how many times, with which arguments, etc – Can wrap an existing method, but the method will still be called – If you need to control what the method will return, use a stub › http://sinonjs.org/docs/#spies MOCKING WITH SINON (1)
  • 15. Daniel Jimenez | 2015-11-01 | Page 15 › Create stubs to replace method implementations with mocked ones – Existing methods are replaced, the original implementation is not executed – Let you specify the return values of a particular method. – Allows complex setup like: › a return value for the Nth call › a return value for specific arguments › Stubs are also spies – When possible choose spies over stubs › http://sinonjs.org/docs/#stubs MOCKING WITH SINON (2)
  • 16. Daniel Jimenez | 2015-11-01 | Page 16 Advanced tips (1) • Create a sinon sandbox in test setup • Sinon stubs/spies in test setup are created using the sandbox • Restore the sandbox in test teardown • Move common test references and type definitions to its own file. • Reference this file in your test files
  • 17. Daniel Jimenez | 2015-11-01 | Page 17 Advanced tips (2) • Try to avoid QUnit asynchronous tests! • Use stubs to return resolved/rejected promises • Use a spy to verify done/fail callbacks • Avoid time-dependent tests! • Use sinon FakeTimers to control Date, setInterval and setTimeout • Use a sandbox to restore the clock between tests
  • 18. Daniel Jimenez | 2015-11-01 | Page 18 Advanced tips (3) • Use object builder pattern with fluent syntax • Useful not only when creating test data but also creating classes under test • Test will support refactorings better • Use sinon matchers and assertions • Test code is more expressive • Avoid checking more than is needed
  • 19. Daniel Jimenez | 2015-11-01 | Page 19 DEMO: writing tests using QUNIT and sinon
  • 21. Daniel Jimenez | 2015-11-01 | Page 21 MANUAL WORKFLOW You can run unit tests just by compiling typescript and using a browser Might be enough for small projects Create tests Write TypeScript tests Create QUnit html test runners Manually manage dependencies by adding scripts in the test runner html file Manually manage paths to the compiled files Compile TS Compile TypeScript code and tests into JavaScript. Some IDE and editors can compile TypeScript automatically You can also manually compile using tsc.exe or Node.js Run in browser Manually open QUnit test runner html files in the browser Every html file has to be opened independently Requires someone to run the tests and interpret the results
  • 22. Daniel Jimenez | 2015-11-01 | Page 22 AUTOMATing the WORKFLOW USING Grunt is a JS Task Runner that can automate tasks like bundling or minification There are hundreds of plugins, including TS compilation and running QUnit tests STEP 4 Text Create tests Write TypeScript tests Create QUnit html test runners Manually manage dependencies by adding scripts in the test runner html file Manually manage paths to the compiled files in the folder Configure Grunt Install grunt-ts for compiling TypeScript Install grunt-contrib-qunit for running QUnit tests Add tasks in your gruntfile for: 1. Clean a temp folder 2. Compile into temp folder 3. Copy html files into temp folder 4. Run QUnit tests Run Grunt Add a “test” task in the gruntfile . It will run the tasks in the full process Run grunt either from the command line (installing grunt-cli) or from an IDE like Visual Studio The full process can be run with a single command, will report test results and the exit code will be non zero if failed http://gruntjs.com/ https://github.com/grunt js/grunt-contrib-qunit https://github.com/Type Strong/grunt-ts
  • 23. Daniel Jimenez | 2015-11-01 | Page 23 SCAFFOLD QUNIT HTML FILES USING You can create your own grunt plugins and tasks Create a task that searches for ///< reference tags and scaffolds the html file STEP 4 Text Create tests Write TypeScript tests Configure Grunt Create task to scaffold QUnit html files Update the tasks in your grunt file as : 1. Clean temp folder 2. Compile into temp folder 3. Scaffold html files into temp folder 4. Run QUnit tests Run Grunt Add a “test” task in the gruntfile . It will run the tasks in the full process Run grunt either from the command line (installing grunt-cli) or from an IDE like Visual Studio The full process can be run with a single command, will report test results and the exit code will be non zero if failed Check example in: https://github.com/DaniJG /TypeScriptUTWorkflows
  • 24. Daniel Jimenez | 2015-11-01 | Page 24 USING EXTERNAL MODULES WITH • Write TypeScript code using external modules via export and import (including your tests) • Specify the module option when compiling TypeScript • Dependencies are loaded by the module system (require.js or common.js) instead of script tags. • Using require.js needs to adjust test startup
  • 25. Daniel Jimenez | 2015-11-01 | Page 25 DEMO: unit testing workflows

Editor's Notes

  1. Demo TypeScriptUTIntro: Show stack source, test code and html test runner Open test in chrome. Add new test for push method and refresh test in chrome (The test will push an item, then calling pop should return the same item)
  2. Demo TypeScriptUT: Add second test in userFormProcessingTest to validate the user will be posted when the validation succeeds. Shared instances for stubs/mocks are created in the startup method. A sandbox is created. Stub for user name validation is configured using withArgs so the stub is only applied when that particular name is validated The validation stub returns a resolved promise, telling the user is valid. User is created with an object builder. (Adding a property or refactor into a class would be easier later) UserFormProcessor (class under test) is also created with an object builder. (Adding/modifying a dependency would be easier) There is a spy to verify the postUser method was called There is another spy to verify the done callback of the asynchronous method we were testing was called The code we are testing and its dependencies are asynchronous, but the whole test can be synchronously run.
  3. 11/17/2015
  4. 11/17/2015
  5. 11/17/2015
  6. Demo TypeScriptUTWorkflows: The Manual one was already modified AutomatedWorkflow You can just run “grunt test” from the command line or tools like VS Add an option to run particular tests like the “-p” argument we have used in Ericsson The code is compiled into a temp folder, you can still open html files from there in chrome and debug Show gruntfile ScaffoldingWorkflow Similar to previous one but there is a new custom task in the gruntfile to generate the html files This task searches for reference tags in the ts code and genereates the html file using a handlebars template Show how we don’t need to worry about writing html files anymore ExternalModulesWorkflow This idea can work with external modules too Code has to be written and compiled using external modules (Using a module loader like require.js) Show compiled JS code The html template has to be modified so we load and start Qunit using require.js