SlideShare a Scribd company logo
1 of 38
Download to read offline
JavaScript TDD with
Jasmine, Karma, and Gulp
All Things Open 2015
Jason Krol
1 / 38
About Me
Jason Krol
! " ShortTompkins
# Kroltech.com
Currently working at:
Dad, Author, Gamer, Geek!
http://ShortTompkins.JS.org
2 / 38
Why should we test?
Google is 2 Billion lines of code!1
Acts as a kind of guarantee
Built-in code documentation!
Testing can be fun?!
3 / 38
Why we probably aren't
Roughly 50% of FE devs aren't testing2
Its time consuming
It can be tedious and difficult
Where to start?!
4 / 38
Tools of the Trade
Jasmine (test/assertion library/framework)
Others: Mocha, Chai, QUnit, et al
Karma (test runner)
Gulp (task runner)
Others: Grunt, Brocolli, npm, make, et al
Requires node.js and npm installed locally
5 / 38
Test Driven Development Crash Course
6 / 38
Test Driven Development Crash Course
Suites, specs, assertions, spies, mocks, stubs,
wtf?!
7 / 38
Test Driven Development Crash Course
Suites, specs, assertions, spies, mocks, stubs,
wtf?!
Describe a piece of code / functionality
being tested
8 / 38
Test Driven Development Crash Course
Suites, specs, assertions, spies, mocks, stubs,
wtf?!
Describe a piece of code / functionality
being tested
Define setup work before and/or after
every test
9 / 38
Test Driven Development Crash Course
Suites, specs, assertions, spies, mocks, stubs,
wtf?!
Describe a piece of code / functionality
being tested
Define setup work before and/or after
every test
It should do exactly what you expect (all
possible scenarios!)
10 / 38
Test Driven Development Crash Course
Suites, specs, assertions, spies, mocks, stubs,
wtf?!
Describe a piece of code / functionality
being tested
Define setup work before and/or after
every test
It should do exactly what you expect (all
possible scenarios!)
Thats it!
11 / 38
Describe
describe('Description/Label', function(){
});
Typically a single word description/label
Can be nested (and very well should be)
12 / 38
beforeEach/afterEach
describe('Description/Label', function(){
beforeEach(function(){
// do some work before every test
});
afterEach(function(){
// do some cleanup/resets after
});
});
13 / 38
it
describe('Description/Label', function(){
beforeEach(function(){ ... });
it('should do something...', function(){
});
it('should also...', function(){
});
});
14 / 38
expect & matchers
describe('Sum', function(){
it('should sum 2 numbers', function(){
expect(sum(1, 1)).toEqual(2);
expect(sum(3, 2)).toEqual(5);
expect(sum(5, 5)).not.toEqual(99);
});
});
15 / 38
Some common matchers:
toBe, toEqual, toMatch, toBeDefined,
toBeUndefined
toBeTruthy, toBeFalsy
toContain, toBeGreaterThan, toBeLessThan
Can be chained with .not
not.toBeDefined(), not.toEqual(0)
Specials:
jasmine.any([Function, Number, String])
jasmine.anything()
16 / 38
Spies
17 / 38
Spies
spyOn(object, 'functionToSpyOn')
jasmine.createSpy('nameOfSpy')
Control spy's behavior:
.and.callThrough()
.and.returnValue(newValue)
.and.callFake(function(){ ... })
Matchers:
.toHaveBeenCalled(),
.toHaveBeenCalledWith(params)
18 / 38
spyOn
describe('Sum', function(){
beforeEach(function() {
spyOn(window, 'alert');
});
it('should alert the sum', function (){
sum(1, 1);
expect(window.alert)
.toHaveBeenCalledWith(2);
});
});
19 / 38
jasmine.createSpy
describe('window.setTimeout', function(){
var cbSpy;
beforeEach(function() {
cbSpy = jasmine.createSpy('cbSpy');
setTimeout(cbSpy, 0);
});
it('should execute callback', function (){
expect(cbSpy).toHaveBeenCalled();
expect(cbSpy).calls.count()).toBe(1);
});
});
20 / 38
Create a quick project
$ mkdir -p jstdd/src/js && cd jstdd
$ touch src/js/sample.js
$ touch src/js/sample_tests.js
21 / 38
File contents:
// sample.js:
function sum(a, b) {
window.alert(a + b);
return a + b;
}
22 / 38
// sample_tests.js:
describe('Sample', function(){
beforeEach(function () {
spyOn(window, 'alert');
});
it('should sum 2 numbers', function(){
expect(sum(1,1)).toEqual(2);
});
it('should alert the value', function(){
sum(2, 2);
expect(window.alert)
.toHaveBeenCalledWith(4);
});
});
23 / 38
Setup our Dev Environment
First, install Karma's CLI as a global package:
$ sudo npm install -g karma-cli phantomjs
24 / 38
Setup our Dev Environment
First, install Karma's CLI as a global package:
$ sudo npm install -g karma-cli phantomjs
Initialize our project:
$ npm init -y
25 / 38
Setup our Dev Environment
First, install Karma's CLI as a global package:
$ sudo npm install -g karma-cli phantomjs
Initialize our project:
$ npm init -y
Locally install karma for the project:
$ npm install --save-dev karma
26 / 38
Initialize Karma for the project:
$ karma init
jasmine
no (Require.js)
PhantomJS
src/js/**/*.js
no exclusions
yes (watch for changes)
27 / 38
Run our first tests!
$ karma start
17 09 2015 22:10:09.116:WARN [karma]: No captured browse
17 09 2015 22:10:09.128:INFO [karma]: Karma v0.
17 09 2015 22:10:09.132:INFO [launcher]: Starting browse
17 09 2015 22:10:10.064:INFO [PhantomJS 1.9.
PhantomJS 1.9.8: Executed 2 of 2 SUCCESS (0.003
|
28 / 38
Introducing Gulp
Why do we need an automated build tool?
29 / 38
Introducing Gulp
Why do we need an automated build tool?
Bundle/Minify our source code
Transpile CSS preprocessors like SASS
ES6 Transpiling (Babel)
Run tests!!
30 / 38
Install Gulp
First, like Karma, globally install the Gulp CLI:
$ sudo npm install -g gulp
31 / 38
Install Gulp
First, like Karma, globally install the Gulp CLI:
$ sudo npm install -g gulp
Locally install gulp and the gulp-karma plugin
for the project:
$ npm install --save-dev gulp gulp-karma
32 / 38
Install Gulp
First, like Karma, globally install the Gulp CLI:
$ sudo npm install -g gulp
Locally install gulp and the gulp-karma plugin
for the project:
$ npm install --save-dev gulp gulp-karma
Create a gulpfile.js:
$ touch gulpfile.js
33 / 38
Gulpfile.js
// gulpfile.js
var gulp = require('gulp'),
karma = require('gulp-karma');
gulp.task('default', function() {
gulp.src(['src/js/**/*.js'])
.pipe(karma({
configFile: 'karma.conf.js',
action: 'watch'
}));
});
34 / 38
Run our first Gulp test task!
$ gulp
[21:37:43] Using gulpfile ~/repos/jstdd/gulpfile.js
[21:37:43] Starting 'default'...
[21:37:43] Finished 'default' after 8.52 ms
[21:37:43] Starting Karma server...
17 09 2015 21:37:44.077:WARN [karma]: No captured browse
17 09 2015 21:37:44.087:INFO [karma]: Karma v0.
17 09 2015 21:37:44.093:INFO [launcher]: Starting browse
17 09 2015 21:37:45.044:INFO [PhantomJS 1.9.
PhantomJS 1.9.8: Executed 2 of 2 SUCCESS (0.003
|
35 / 38
Lets look at some real tests!
VideoPlayer.js & VideoPlayer_tests.js
Basic video player module
Uses jQuery
12 functions (100 lines)
46 tests (over 300 lines)
36 / 38
Resources
Jasmine Docs: http://jasmine.github.io/
Karma: http://karma-runner.github.io/
Gulp: http://gulpjs.com/
Sources
1. http://www.wired.com/2015/09/google-2-
billion-lines-codeand-one-place/
2. http://ashleynolan.co.uk/blog/frontend-
tooling-survey-2015-results
37 / 38
Start Testing!!
38 / 38

More Related Content

What's hot

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
 
Introduction to Python Celery
Introduction to Python CeleryIntroduction to Python Celery
Introduction to Python CeleryMahendra M
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsGraham Dumpleton
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play appsYevgeniy Brikman
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Yevgeniy Brikman
 
Data processing with celery and rabbit mq
Data processing with celery and rabbit mqData processing with celery and rabbit mq
Data processing with celery and rabbit mqJeff Peck
 
Jenkins Evolutions - JEEConf 2012
Jenkins Evolutions - JEEConf 2012Jenkins Evolutions - JEEConf 2012
Jenkins Evolutions - JEEConf 2012Anton Arhipov
 
Google App Engine With Java And Groovy
Google App Engine With Java And GroovyGoogle App Engine With Java And Groovy
Google App Engine With Java And GroovyKen Kousen
 
Automated acceptance test
Automated acceptance testAutomated acceptance test
Automated acceptance testBryan Liu
 
Unit testing of spark applications
Unit testing of spark applicationsUnit testing of spark applications
Unit testing of spark applicationsKnoldus Inc.
 
Survive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksSurvive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksJuho Vepsäläinen
 
AngularJS Unit Testing
AngularJS Unit TestingAngularJS Unit Testing
AngularJS Unit TestingPrince Norin
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programmingEric Polerecky
 
Unit Testing with Jest
Unit Testing with JestUnit Testing with Jest
Unit Testing with JestMaayan Glikser
 
London Hashicorp Meetup #8 - Testing Programmable Infrastructure By Matt Long
London Hashicorp Meetup #8 -  Testing Programmable Infrastructure By Matt LongLondon Hashicorp Meetup #8 -  Testing Programmable Infrastructure By Matt Long
London Hashicorp Meetup #8 - Testing Programmable Infrastructure By Matt LongOpenCredo
 
Spark summit2014 techtalk - testing spark
Spark summit2014 techtalk - testing sparkSpark summit2014 techtalk - testing spark
Spark summit2014 techtalk - testing sparkAnu Shetty
 
Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017Matthew Groves
 

What's hot (20)

Celery with python
Celery with pythonCelery with python
Celery with python
 
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
 
Introduction to Python Celery
Introduction to Python CeleryIntroduction to Python Celery
Introduction to Python Celery
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web Applications
 
JavaCro'14 - Is there Kotlin after Java 8 – Ivan Turčinović and Igor Buzatović
JavaCro'14 - Is there Kotlin after Java 8 – Ivan Turčinović and Igor BuzatovićJavaCro'14 - Is there Kotlin after Java 8 – Ivan Turčinović and Igor Buzatović
JavaCro'14 - Is there Kotlin after Java 8 – Ivan Turčinović and Igor Buzatović
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
 
Data processing with celery and rabbit mq
Data processing with celery and rabbit mqData processing with celery and rabbit mq
Data processing with celery and rabbit mq
 
Testing Ansible
Testing AnsibleTesting Ansible
Testing Ansible
 
Jenkins Evolutions - JEEConf 2012
Jenkins Evolutions - JEEConf 2012Jenkins Evolutions - JEEConf 2012
Jenkins Evolutions - JEEConf 2012
 
Google App Engine With Java And Groovy
Google App Engine With Java And GroovyGoogle App Engine With Java And Groovy
Google App Engine With Java And Groovy
 
Automated acceptance test
Automated acceptance testAutomated acceptance test
Automated acceptance test
 
Unit testing of spark applications
Unit testing of spark applicationsUnit testing of spark applications
Unit testing of spark applications
 
Survive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksSurvive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and Tricks
 
AngularJS Unit Testing
AngularJS Unit TestingAngularJS Unit Testing
AngularJS Unit Testing
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programming
 
Unit Testing with Jest
Unit Testing with JestUnit Testing with Jest
Unit Testing with Jest
 
London Hashicorp Meetup #8 - Testing Programmable Infrastructure By Matt Long
London Hashicorp Meetup #8 -  Testing Programmable Infrastructure By Matt LongLondon Hashicorp Meetup #8 -  Testing Programmable Infrastructure By Matt Long
London Hashicorp Meetup #8 - Testing Programmable Infrastructure By Matt Long
 
Spark summit2014 techtalk - testing spark
Spark summit2014 techtalk - testing sparkSpark summit2014 techtalk - testing spark
Spark summit2014 techtalk - testing spark
 
Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017
 

Similar to Javascript TDD with Jasmine, Karma, and Gulp

Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacriptLei Kang
 
Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008Andrea Francia
 
DevSecCon London 2017 - MacOS security, hardening and forensics 101 by Ben Hu...
DevSecCon London 2017 - MacOS security, hardening and forensics 101 by Ben Hu...DevSecCon London 2017 - MacOS security, hardening and forensics 101 by Ben Hu...
DevSecCon London 2017 - MacOS security, hardening and forensics 101 by Ben Hu...DevSecCon
 
Writing Apps with HotCocoa and MacRuby
Writing Apps with HotCocoa and MacRubyWriting Apps with HotCocoa and MacRuby
Writing Apps with HotCocoa and MacRubyRenzo Borgatti
 
JUDCon London 2011 - Bin packing with drools planner by example
JUDCon London 2011 - Bin packing with drools planner by exampleJUDCon London 2011 - Bin packing with drools planner by example
JUDCon London 2011 - Bin packing with drools planner by exampleGeoffrey De Smet
 
What is new with JavaScript in Gnome: The 2021 edition
What is new with JavaScript in Gnome: The 2021 editionWhat is new with JavaScript in Gnome: The 2021 edition
What is new with JavaScript in Gnome: The 2021 editionIgalia
 
不深不淺,帶你認識 LLVM (Found LLVM in your life)
不深不淺,帶你認識 LLVM (Found LLVM in your life)不深不淺,帶你認識 LLVM (Found LLVM in your life)
不深不淺,帶你認識 LLVM (Found LLVM in your life)Douglas Chen
 
Moving from Jenkins 1 to 2 declarative pipeline adventures
Moving from Jenkins 1 to 2 declarative pipeline adventuresMoving from Jenkins 1 to 2 declarative pipeline adventures
Moving from Jenkins 1 to 2 declarative pipeline adventuresFrits Van Der Holst
 
Beyond Parallelize and Collect by Holden Karau
Beyond Parallelize and Collect by Holden KarauBeyond Parallelize and Collect by Holden Karau
Beyond Parallelize and Collect by Holden KarauSpark Summit
 
Mock cli with Python unittest
Mock cli with Python unittestMock cli with Python unittest
Mock cli with Python unittestSong Jin
 
닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기YoungSu Son
 
Google mock training
Google mock trainingGoogle mock training
Google mock trainingThierry Gayet
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVMSylvain Wallez
 
2012 02-04 fosdem 2012 - drools planner
2012 02-04 fosdem 2012 - drools planner2012 02-04 fosdem 2012 - drools planner
2012 02-04 fosdem 2012 - drools plannerGeoffrey De Smet
 
Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)William Farrell
 
Command Line Applications with Ruby
Command Line Applications with RubyCommand Line Applications with Ruby
Command Line Applications with RubyAlexander Merkulov
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Sylvain Wallez
 

Similar to Javascript TDD with Jasmine, Karma, and Gulp (20)

Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacript
 
Why Gradle?
Why Gradle?Why Gradle?
Why Gradle?
 
A Life of breakpoint
A Life of breakpointA Life of breakpoint
A Life of breakpoint
 
Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008
 
DevSecCon London 2017 - MacOS security, hardening and forensics 101 by Ben Hu...
DevSecCon London 2017 - MacOS security, hardening and forensics 101 by Ben Hu...DevSecCon London 2017 - MacOS security, hardening and forensics 101 by Ben Hu...
DevSecCon London 2017 - MacOS security, hardening and forensics 101 by Ben Hu...
 
Writing Apps with HotCocoa and MacRuby
Writing Apps with HotCocoa and MacRubyWriting Apps with HotCocoa and MacRuby
Writing Apps with HotCocoa and MacRuby
 
JUDCon London 2011 - Bin packing with drools planner by example
JUDCon London 2011 - Bin packing with drools planner by exampleJUDCon London 2011 - Bin packing with drools planner by example
JUDCon London 2011 - Bin packing with drools planner by example
 
What is new with JavaScript in Gnome: The 2021 edition
What is new with JavaScript in Gnome: The 2021 editionWhat is new with JavaScript in Gnome: The 2021 edition
What is new with JavaScript in Gnome: The 2021 edition
 
不深不淺,帶你認識 LLVM (Found LLVM in your life)
不深不淺,帶你認識 LLVM (Found LLVM in your life)不深不淺,帶你認識 LLVM (Found LLVM in your life)
不深不淺,帶你認識 LLVM (Found LLVM in your life)
 
Moving from Jenkins 1 to 2 declarative pipeline adventures
Moving from Jenkins 1 to 2 declarative pipeline adventuresMoving from Jenkins 1 to 2 declarative pipeline adventures
Moving from Jenkins 1 to 2 declarative pipeline adventures
 
Beyond Parallelize and Collect by Holden Karau
Beyond Parallelize and Collect by Holden KarauBeyond Parallelize and Collect by Holden Karau
Beyond Parallelize and Collect by Holden Karau
 
Mock cli with Python unittest
Mock cli with Python unittestMock cli with Python unittest
Mock cli with Python unittest
 
닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기
 
Google mock training
Google mock trainingGoogle mock training
Google mock training
 
Testing in go
Testing in goTesting in go
Testing in go
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVM
 
2012 02-04 fosdem 2012 - drools planner
2012 02-04 fosdem 2012 - drools planner2012 02-04 fosdem 2012 - drools planner
2012 02-04 fosdem 2012 - drools planner
 
Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)
 
Command Line Applications with Ruby
Command Line Applications with RubyCommand Line Applications with Ruby
Command Line Applications with Ruby
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!
 

More from All Things Open

Building Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityBuilding Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityAll Things Open
 
Modern Database Best Practices
Modern Database Best PracticesModern Database Best Practices
Modern Database Best PracticesAll Things Open
 
Open Source and Public Policy
Open Source and Public PolicyOpen Source and Public Policy
Open Source and Public PolicyAll Things Open
 
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...All Things Open
 
The State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashThe State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashAll Things Open
 
Total ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptTotal ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptAll Things Open
 
What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?All Things Open
 
How to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractHow to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractAll Things Open
 
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlowAll Things Open
 
DEI Challenges and Success
DEI Challenges and SuccessDEI Challenges and Success
DEI Challenges and SuccessAll Things Open
 
Scaling Web Applications with Background
Scaling Web Applications with BackgroundScaling Web Applications with Background
Scaling Web Applications with BackgroundAll Things Open
 
Supercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblySupercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblyAll Things Open
 
Using SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksUsing SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksAll Things Open
 
Configuration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptConfiguration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptAll Things Open
 
Scaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramScaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramAll Things Open
 
Build Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceBuild Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceAll Things Open
 
Deploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamDeploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamAll Things Open
 
Sudo – Giving access while staying in control
Sudo – Giving access while staying in controlSudo – Giving access while staying in control
Sudo – Giving access while staying in controlAll Things Open
 
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsFortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsAll Things Open
 
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...All Things Open
 

More from All Things Open (20)

Building Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityBuilding Reliability - The Realities of Observability
Building Reliability - The Realities of Observability
 
Modern Database Best Practices
Modern Database Best PracticesModern Database Best Practices
Modern Database Best Practices
 
Open Source and Public Policy
Open Source and Public PolicyOpen Source and Public Policy
Open Source and Public Policy
 
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
 
The State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashThe State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil Nash
 
Total ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptTotal ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScript
 
What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?
 
How to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractHow to Write & Deploy a Smart Contract
How to Write & Deploy a Smart Contract
 
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 
DEI Challenges and Success
DEI Challenges and SuccessDEI Challenges and Success
DEI Challenges and Success
 
Scaling Web Applications with Background
Scaling Web Applications with BackgroundScaling Web Applications with Background
Scaling Web Applications with Background
 
Supercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblySupercharging tutorials with WebAssembly
Supercharging tutorials with WebAssembly
 
Using SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksUsing SQL to Find Needles in Haystacks
Using SQL to Find Needles in Haystacks
 
Configuration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptConfiguration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit Intercept
 
Scaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramScaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship Program
 
Build Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceBuild Developer Experience Teams for Open Source
Build Developer Experience Teams for Open Source
 
Deploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamDeploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache Beam
 
Sudo – Giving access while staying in control
Sudo – Giving access while staying in controlSudo – Giving access while staying in control
Sudo – Giving access while staying in control
 
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsFortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
 
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
 

Recently uploaded

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 

Recently uploaded (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 

Javascript TDD with Jasmine, Karma, and Gulp

  • 1. JavaScript TDD with Jasmine, Karma, and Gulp All Things Open 2015 Jason Krol 1 / 38
  • 2. About Me Jason Krol ! " ShortTompkins # Kroltech.com Currently working at: Dad, Author, Gamer, Geek! http://ShortTompkins.JS.org 2 / 38
  • 3. Why should we test? Google is 2 Billion lines of code!1 Acts as a kind of guarantee Built-in code documentation! Testing can be fun?! 3 / 38
  • 4. Why we probably aren't Roughly 50% of FE devs aren't testing2 Its time consuming It can be tedious and difficult Where to start?! 4 / 38
  • 5. Tools of the Trade Jasmine (test/assertion library/framework) Others: Mocha, Chai, QUnit, et al Karma (test runner) Gulp (task runner) Others: Grunt, Brocolli, npm, make, et al Requires node.js and npm installed locally 5 / 38
  • 6. Test Driven Development Crash Course 6 / 38
  • 7. Test Driven Development Crash Course Suites, specs, assertions, spies, mocks, stubs, wtf?! 7 / 38
  • 8. Test Driven Development Crash Course Suites, specs, assertions, spies, mocks, stubs, wtf?! Describe a piece of code / functionality being tested 8 / 38
  • 9. Test Driven Development Crash Course Suites, specs, assertions, spies, mocks, stubs, wtf?! Describe a piece of code / functionality being tested Define setup work before and/or after every test 9 / 38
  • 10. Test Driven Development Crash Course Suites, specs, assertions, spies, mocks, stubs, wtf?! Describe a piece of code / functionality being tested Define setup work before and/or after every test It should do exactly what you expect (all possible scenarios!) 10 / 38
  • 11. Test Driven Development Crash Course Suites, specs, assertions, spies, mocks, stubs, wtf?! Describe a piece of code / functionality being tested Define setup work before and/or after every test It should do exactly what you expect (all possible scenarios!) Thats it! 11 / 38
  • 12. Describe describe('Description/Label', function(){ }); Typically a single word description/label Can be nested (and very well should be) 12 / 38
  • 13. beforeEach/afterEach describe('Description/Label', function(){ beforeEach(function(){ // do some work before every test }); afterEach(function(){ // do some cleanup/resets after }); }); 13 / 38
  • 14. it describe('Description/Label', function(){ beforeEach(function(){ ... }); it('should do something...', function(){ }); it('should also...', function(){ }); }); 14 / 38
  • 15. expect & matchers describe('Sum', function(){ it('should sum 2 numbers', function(){ expect(sum(1, 1)).toEqual(2); expect(sum(3, 2)).toEqual(5); expect(sum(5, 5)).not.toEqual(99); }); }); 15 / 38
  • 16. Some common matchers: toBe, toEqual, toMatch, toBeDefined, toBeUndefined toBeTruthy, toBeFalsy toContain, toBeGreaterThan, toBeLessThan Can be chained with .not not.toBeDefined(), not.toEqual(0) Specials: jasmine.any([Function, Number, String]) jasmine.anything() 16 / 38
  • 18. Spies spyOn(object, 'functionToSpyOn') jasmine.createSpy('nameOfSpy') Control spy's behavior: .and.callThrough() .and.returnValue(newValue) .and.callFake(function(){ ... }) Matchers: .toHaveBeenCalled(), .toHaveBeenCalledWith(params) 18 / 38
  • 19. spyOn describe('Sum', function(){ beforeEach(function() { spyOn(window, 'alert'); }); it('should alert the sum', function (){ sum(1, 1); expect(window.alert) .toHaveBeenCalledWith(2); }); }); 19 / 38
  • 20. jasmine.createSpy describe('window.setTimeout', function(){ var cbSpy; beforeEach(function() { cbSpy = jasmine.createSpy('cbSpy'); setTimeout(cbSpy, 0); }); it('should execute callback', function (){ expect(cbSpy).toHaveBeenCalled(); expect(cbSpy).calls.count()).toBe(1); }); }); 20 / 38
  • 21. Create a quick project $ mkdir -p jstdd/src/js && cd jstdd $ touch src/js/sample.js $ touch src/js/sample_tests.js 21 / 38
  • 22. File contents: // sample.js: function sum(a, b) { window.alert(a + b); return a + b; } 22 / 38
  • 23. // sample_tests.js: describe('Sample', function(){ beforeEach(function () { spyOn(window, 'alert'); }); it('should sum 2 numbers', function(){ expect(sum(1,1)).toEqual(2); }); it('should alert the value', function(){ sum(2, 2); expect(window.alert) .toHaveBeenCalledWith(4); }); }); 23 / 38
  • 24. Setup our Dev Environment First, install Karma's CLI as a global package: $ sudo npm install -g karma-cli phantomjs 24 / 38
  • 25. Setup our Dev Environment First, install Karma's CLI as a global package: $ sudo npm install -g karma-cli phantomjs Initialize our project: $ npm init -y 25 / 38
  • 26. Setup our Dev Environment First, install Karma's CLI as a global package: $ sudo npm install -g karma-cli phantomjs Initialize our project: $ npm init -y Locally install karma for the project: $ npm install --save-dev karma 26 / 38
  • 27. Initialize Karma for the project: $ karma init jasmine no (Require.js) PhantomJS src/js/**/*.js no exclusions yes (watch for changes) 27 / 38
  • 28. Run our first tests! $ karma start 17 09 2015 22:10:09.116:WARN [karma]: No captured browse 17 09 2015 22:10:09.128:INFO [karma]: Karma v0. 17 09 2015 22:10:09.132:INFO [launcher]: Starting browse 17 09 2015 22:10:10.064:INFO [PhantomJS 1.9. PhantomJS 1.9.8: Executed 2 of 2 SUCCESS (0.003 | 28 / 38
  • 29. Introducing Gulp Why do we need an automated build tool? 29 / 38
  • 30. Introducing Gulp Why do we need an automated build tool? Bundle/Minify our source code Transpile CSS preprocessors like SASS ES6 Transpiling (Babel) Run tests!! 30 / 38
  • 31. Install Gulp First, like Karma, globally install the Gulp CLI: $ sudo npm install -g gulp 31 / 38
  • 32. Install Gulp First, like Karma, globally install the Gulp CLI: $ sudo npm install -g gulp Locally install gulp and the gulp-karma plugin for the project: $ npm install --save-dev gulp gulp-karma 32 / 38
  • 33. Install Gulp First, like Karma, globally install the Gulp CLI: $ sudo npm install -g gulp Locally install gulp and the gulp-karma plugin for the project: $ npm install --save-dev gulp gulp-karma Create a gulpfile.js: $ touch gulpfile.js 33 / 38
  • 34. Gulpfile.js // gulpfile.js var gulp = require('gulp'), karma = require('gulp-karma'); gulp.task('default', function() { gulp.src(['src/js/**/*.js']) .pipe(karma({ configFile: 'karma.conf.js', action: 'watch' })); }); 34 / 38
  • 35. Run our first Gulp test task! $ gulp [21:37:43] Using gulpfile ~/repos/jstdd/gulpfile.js [21:37:43] Starting 'default'... [21:37:43] Finished 'default' after 8.52 ms [21:37:43] Starting Karma server... 17 09 2015 21:37:44.077:WARN [karma]: No captured browse 17 09 2015 21:37:44.087:INFO [karma]: Karma v0. 17 09 2015 21:37:44.093:INFO [launcher]: Starting browse 17 09 2015 21:37:45.044:INFO [PhantomJS 1.9. PhantomJS 1.9.8: Executed 2 of 2 SUCCESS (0.003 | 35 / 38
  • 36. Lets look at some real tests! VideoPlayer.js & VideoPlayer_tests.js Basic video player module Uses jQuery 12 functions (100 lines) 46 tests (over 300 lines) 36 / 38
  • 37. Resources Jasmine Docs: http://jasmine.github.io/ Karma: http://karma-runner.github.io/ Gulp: http://gulpjs.com/ Sources 1. http://www.wired.com/2015/09/google-2- billion-lines-codeand-one-place/ 2. http://ashleynolan.co.uk/blog/frontend- tooling-survey-2015-results 37 / 38