SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Testable Javascript

   MARK ETHAN TROSTLERmark@zzo.com
                  @zzoass
      http://randomgoo.blogspot.com/
“If today were the last day
of my life, would I want to
 do what I am about to do
          today?”
KISS
Minimize Your Pain

•Write Small
•Write Simple
•Test Early
•Test Often
Write Small – Write Simple

 •Isolate code to test
 •Loosely couple
 dependencies
 •Be obvious
 •Optimize last
Test Early – Test Often



       Test Now
Explicit Dependencies
How things can go wrong…
// Call x.flub with twice z
function foo(z) {
varx = new X(); // Mmmmmtightly coupled…
    return x.flub(z*2);
}

// We want to test if x.flub was called with 14
var back = foo(7);
// But only have „back‟ to test!


                                            November 9, 2011
How can we test only our
                 code?
// Call x.flub with twice z
function foo(x, z) {
    return x.flub(z*2);
}

// Test x.flub got called with 14…
varx = new MockX(),
foo(x, 7);

If (x.called(„flub‟).with(14)) {
    // a winner!!
}
                                     November 9, 2011
Really see this in constructors…
// Ewww – not directly testable
function MyObject() {
this.x = new X();
}

MyObject.Prototpe.foo = function(z) {
  return this.x.flub(z*2);
}

var test = new MyObject(),
  back = test.foo(7) // cannot test what foo() did
                                           November 9, 2011
Inject It - Constructor
// Yea! Testable!
function MyObject(x) {
this.x = x;
}
MyObject.Prototpe.foo = function(z) {
    return this.x.flub(z*2);
}

varx = new MockX(), test = new MyObject(x);

test.foo(7);
If (x.called(„flub‟, with(14)) {
    // We tested only our function!
}                                             November 9, 2011
Inject It - Setter
// Yea! Testable!
function MyObject() { }
MyObject.prototpe.setX= function(x) {
this.x = x;
};
MyObject.prototpe.foo = function(z) {
      return this.x.flub(z*2);
};
varx = new MockX(), test = new MyObject();
test.setX(x);
test.foo(7);
If (x.called(„flub‟, with(14)) {
    // We tested only our function!
}                                            November 9, 2011
YUI
YUI Explicit Dependencies
YUI.add(„myObject‟, function(Y) {
     // Code you want to test
Y.MyObject = function() {
this.a = new Y.a();
this.b = new Y.b();
this.c = new Y.c();
    };
}, { requires: [ „a‟, „b‟, „c‟ ] });

YUI.use(„myObject‟, function(Y) {
    new Y.MyObject();
                                       November 9, 2011
});
Injecting YUI3 Dependencies??

YUI.add(„myObject‟, function(Y) {
     //// Code you want to test
Y.MyObject = function(a, b, c) {
this.a = a;
this.b = b;
this.c = c;
    };
});
YUI.use(„myObject‟, „a‟, „b‟, „c‟, function(Y) { // Prod
     new Y.MyObject(newY.a(), new Y.b(), new Y.c());
});
YUI.use(„myObject‟, „test‟, function(Y) { // Test
 new Y.MyObject(Y.Mock(), Y.Mock(), Y.Mock());
                                                           November 9, 2011
});
Isolating Dependencies
<script src =“yui3.js”></script>
<script src =“a.mock.js”></script>
<script src =“b.mock.js”></script>
<script src =“c.mock.js”></script>
<script src =“myObject.js”></script>

<script>
YUI.use(„myObject‟, function(Y) {
  new Y.MyObject();
</script>
                                       November 9, 2011
Injecting YUI3 Dependencies

YUI.add(„myObject‟, function(Y) {
     //// Code you want to test
Y.MyObject = function(a, b, c) {
this.a = a || new Y.a();
this.b = b|| new Y.b();
this.c = c|| new Y.c();
    };
}, { requires: [„a‟, „b‟, „c‟ ] });
YUI.use(„myObject‟, function(Y) { // Prod
     new Y.MyObject();
});
YUI.use(„myObject‟, „test‟, function(Y) { // Test
 new Y.MyObject(Y.Mock(), Y.Mock(), Y.Mock());
});                                                 November 9, 2011
Injecting YUI3 Dependencies
YUI.add(„myObject‟, function(Y) {
     //// Code you want to test
Y.MyObject = function() {
     }
Y.MyObject.prototype.setX = function(x) {
this.x = x;
     };
}, { requires: [„a‟, „b‟, „c‟ ] });
YUI.use(„myObject‟, function(Y) { // Prod
     new Y.MyObject();
});
YUI.use(„myObject‟, „test‟, function(Y) { // Test
 new Y.MyObject().setX(Y.Mock());
});                                                 November 9, 2011
Isolating Dependencies

YUI({
    modules: {
         a: {
fullpath: ‟/a-mock.js'
         }
      }
}).use('test', ‟myObject', 'console', function(
    Y) {
varobj = new Y.MyObject();
                                             November 9, 2011
});
Isolating Dependencies

YUI({
    filter: mock:
{ 'searchExp': “.js",
'replaceStr': "-mock.js" }
}).use('test', ‟myObject', 'console', function(
     Y) {
varobj = new Y.MyObject();
});

                                            November 9, 2011
Mock Objects
Mock Object

YUI().add(‟a', function(Y) {
    Y.A= function() {
var me = Y.Mock();
Y.Mock.expect(me, {
           method: ”render",
args: [„#toolbar‟]
       });
       return me;
    }
}, '1.0.0' ,{requires:['test']});   November 9, 2011
Testing with Mocked
           Dependencies

YUI().add(‟a', function(Y) {
    Y.A= function() { return Y.Mock(); };
}, '1.0.0' ,{requires:['test']});
YUI().use(„a‟, „test‟, „myObject‟, function(Y) {
var a = new Y.A();
Y.Mock.expect(a, {
            method: ”render",
args: [„#toolbar‟]
        });
    new MyObject(a).render();
    //// verify a.render(„#toolbar‟) was called
});                                                November 9, 2011
Implicit Dependencies
„Hidden‟ Dependencies
   Private functions are „hidden‟ dependencies
   Cannot test by definition!
   Make public? Are they part of the public API??
   Mock them out?? How??

 Refactor private function to be explicit
  dependencies
 Minimize their use – they cannot be tested
  directly
 Treated exactly like any other dependency
                                               November 9, 2011
Private functions

YOU CANNOT TEST
     THEM!


                      November 9, 2011
Don‟t forget browser
             dependencies!

YUI.add(„myObject‟, function(Y) {
     //// Code you want to test
Y.MyObject = function(window) {
this.window = window;
    };
myObject.prototype.fiddle = function(str) { return
       window.escape(str + „ FOOBIE‟); };
});

YUI.use(„myObject‟, function(Y) {
varwinMock = new WindowMock(),
myObj = new myObject(winMock);
myObj.fiddle(„foobie‟); // Check WindowMock!!
}
                                                     November 9, 2011
Recap
Explicit Deps

Problem: Public dependencies
Symptom: Explicitly declared
  dependencies
Cure:
• Eliminate tightly coupled code/use
  injection
• Pre-load mock‟ed versions of public
  dependencies

                                   November 9, 2011
Private Deps

Problem: Private dependencies
Symptom: Private methods and
  functions
Cure:
• Minimize private dependencies
• Make public dependency
• Use composition to pull in private stuff

                                      November 9, 2011
Browser Deps

Problem: Browser dependencies
Symptom: „window‟ or global scope
  usage
Cure:
• Eliminate tightly coupled code/use
  injection
• Pre-load mock‟ed versions of public
  dependencies

                                   November 9, 2011
Unit Testing Principles &
       Practices
All about dependency management

Identify dependencies and mock
  them out

Do not take your environment for
  granted

                              November 9, 2011
“Don‟t Be Foolish”
Resources

• https://github.com/zzo/JUTE
• trostler@yahoo-inc.com
• @zzoass
• http://randomgoo.blogspot.com/


                                November 9, 2011

Weitere ähnliche Inhalte

Was ist angesagt?

Get started with YUI
Get started with YUIGet started with YUI
Get started with YUIAdam Lu
 
Zend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinarZend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinarYonni Mendes
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
 
Javascript And J Query
Javascript And J QueryJavascript And J Query
Javascript And J Queryitsarsalan
 
Java script object model
Java script object modelJava script object model
Java script object modelJames Hsieh
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureNicholas Zakas
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performancejohndaviddalton
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingCodemotion
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized军 沈
 
Javascript 攻佔桌面應用程式:使用 electron
Javascript 攻佔桌面應用程式:使用 electronJavascript 攻佔桌面應用程式:使用 electron
Javascript 攻佔桌面應用程式:使用 electronYao Nien Chung
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Chaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreChaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreNicolas Carlo
 

Was ist angesagt? (20)

Get started with YUI
Get started with YUIGet started with YUI
Get started with YUI
 
meet.js - QooXDoo
meet.js - QooXDoomeet.js - QooXDoo
meet.js - QooXDoo
 
Zend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinarZend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinar
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Javascript And J Query
Javascript And J QueryJavascript And J Query
Javascript And J Query
 
Prototype
PrototypePrototype
Prototype
 
Java script object model
Java script object modelJava script object model
Java script object model
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performance
 
JDK Power Tools
JDK Power ToolsJDK Power Tools
JDK Power Tools
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
 
Javascript 攻佔桌面應用程式:使用 electron
Javascript 攻佔桌面應用程式:使用 electronJavascript 攻佔桌面應用程式:使用 electron
Javascript 攻佔桌面應用程式:使用 electron
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Chaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreChaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscore
 

Andere mochten auch

Высший арбитражный суд конкретизировал ответственность генеральных директор...
Высший арбитражный суд конкретизировал ответственность генеральных директор...Высший арбитражный суд конкретизировал ответственность генеральных директор...
Высший арбитражный суд конкретизировал ответственность генеральных директор...GreenfieldProject
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009David Pollak
 
Supporting the complex requirements of a long-term project for whole brain em...
Supporting the complex requirements of a long-term project for whole brain em...Supporting the complex requirements of a long-term project for whole brain em...
Supporting the complex requirements of a long-term project for whole brain em...Randal Koene
 
Anforderungen an die Wissensrepräsentation im Social Semantic Web
Anforderungen an die Wissensrepräsentation im Social Semantic WebAnforderungen an die Wissensrepräsentation im Social Semantic Web
Anforderungen an die Wissensrepräsentation im Social Semantic WebKatrin Weller
 
Barometr Nastrojow Ekonomicznych Luty
Barometr Nastrojow  Ekonomicznych LutyBarometr Nastrojow  Ekonomicznych Luty
Barometr Nastrojow Ekonomicznych Lutyprnews
 
Cоциальные сети. выбор оптимальной площадки для бренда автомобильной отрасли
Cоциальные сети. выбор оптимальной площадки для бренда автомобильной отраслиCоциальные сети. выбор оптимальной площадки для бренда автомобильной отрасли
Cоциальные сети. выбор оптимальной площадки для бренда автомобильной отраслиPR News
 
Виральные кейсы Real Time PR
Виральные кейсы Real Time PRВиральные кейсы Real Time PR
Виральные кейсы Real Time PRPR News
 
Behavioral Targeting Webinar
Behavioral Targeting WebinarBehavioral Targeting Webinar
Behavioral Targeting WebinarRemko Zuiderwijk
 
Lecture: Semantic Word Clouds
Lecture: Semantic Word CloudsLecture: Semantic Word Clouds
Lecture: Semantic Word CloudsMarina Santini
 

Andere mochten auch (9)

Высший арбитражный суд конкретизировал ответственность генеральных директор...
Высший арбитражный суд конкретизировал ответственность генеральных директор...Высший арбитражный суд конкретизировал ответственность генеральных директор...
Высший арбитражный суд конкретизировал ответственность генеральных директор...
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
 
Supporting the complex requirements of a long-term project for whole brain em...
Supporting the complex requirements of a long-term project for whole brain em...Supporting the complex requirements of a long-term project for whole brain em...
Supporting the complex requirements of a long-term project for whole brain em...
 
Anforderungen an die Wissensrepräsentation im Social Semantic Web
Anforderungen an die Wissensrepräsentation im Social Semantic WebAnforderungen an die Wissensrepräsentation im Social Semantic Web
Anforderungen an die Wissensrepräsentation im Social Semantic Web
 
Barometr Nastrojow Ekonomicznych Luty
Barometr Nastrojow  Ekonomicznych LutyBarometr Nastrojow  Ekonomicznych Luty
Barometr Nastrojow Ekonomicznych Luty
 
Cоциальные сети. выбор оптимальной площадки для бренда автомобильной отрасли
Cоциальные сети. выбор оптимальной площадки для бренда автомобильной отраслиCоциальные сети. выбор оптимальной площадки для бренда автомобильной отрасли
Cоциальные сети. выбор оптимальной площадки для бренда автомобильной отрасли
 
Виральные кейсы Real Time PR
Виральные кейсы Real Time PRВиральные кейсы Real Time PR
Виральные кейсы Real Time PR
 
Behavioral Targeting Webinar
Behavioral Targeting WebinarBehavioral Targeting Webinar
Behavioral Targeting Webinar
 
Lecture: Semantic Word Clouds
Lecture: Semantic Word CloudsLecture: Semantic Word Clouds
Lecture: Semantic Word Clouds
 

Ähnlich wie Testable Javascript

YUI3 Modules
YUI3 ModulesYUI3 Modules
YUI3 Modulesa_pipkin
 
Javascript essential-pattern
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern偉格 高
 
Nashville Symfony Functional Testing
Nashville Symfony Functional TestingNashville Symfony Functional Testing
Nashville Symfony Functional TestingBrent Shaffer
 
Android testing
Android testingAndroid testing
Android testingSean Tsai
 
So, you think you know widgets.
So, you think you know widgets.So, you think you know widgets.
So, you think you know widgets.danielericlee
 
Jquery plugin development
Jquery plugin developmentJquery plugin development
Jquery plugin developmentFaruk Hossen
 
YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)Nicholas Zakas
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald Sipe
 
My Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveCMy Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveCJohnKennedy
 
Node conf - building realtime webapps
Node conf - building realtime webappsNode conf - building realtime webapps
Node conf - building realtime webappsHenrik Joreteg
 
PHP Unit Testing in Yii
PHP Unit Testing in YiiPHP Unit Testing in Yii
PHP Unit Testing in YiiIlPeach
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery PluginRavi Mone
 
2009 Hackday Taiwan Yui
2009 Hackday Taiwan Yui2009 Hackday Taiwan Yui
2009 Hackday Taiwan YuiJH Lee
 

Ähnlich wie Testable Javascript (20)

YUI3 Modules
YUI3 ModulesYUI3 Modules
YUI3 Modules
 
has("builds")
has("builds")has("builds")
has("builds")
 
Javascript essential-pattern
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern
 
Nashville Symfony Functional Testing
Nashville Symfony Functional TestingNashville Symfony Functional Testing
Nashville Symfony Functional Testing
 
Android testing
Android testingAndroid testing
Android testing
 
So, you think you know widgets.
So, you think you know widgets.So, you think you know widgets.
So, you think you know widgets.
 
Jquery plugin development
Jquery plugin developmentJquery plugin development
Jquery plugin development
 
YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
My Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveCMy Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveC
 
Node conf - building realtime webapps
Node conf - building realtime webappsNode conf - building realtime webapps
Node conf - building realtime webapps
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
PHP Unit Testing in Yii
PHP Unit Testing in YiiPHP Unit Testing in Yii
PHP Unit Testing in Yii
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery Plugin
 
4front en
4front en4front en
4front en
 
DrupalCon jQuery
DrupalCon jQueryDrupalCon jQuery
DrupalCon jQuery
 
2009 Hackday Taiwan Yui
2009 Hackday Taiwan Yui2009 Hackday Taiwan Yui
2009 Hackday Taiwan Yui
 

Kürzlich hochgeladen

Organizational Transformation Lead with Culture
Organizational Transformation Lead with CultureOrganizational Transformation Lead with Culture
Organizational Transformation Lead with CultureSeta Wicaksana
 
Pre Engineered Building Manufacturers Hyderabad.pptx
Pre Engineered  Building Manufacturers Hyderabad.pptxPre Engineered  Building Manufacturers Hyderabad.pptx
Pre Engineered Building Manufacturers Hyderabad.pptxRoofing Contractor
 
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGParadip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGpr788182
 
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...ssuserf63bd7
 
Lucknow Housewife Escorts by Sexy Bhabhi Service 8250092165
Lucknow Housewife Escorts  by Sexy Bhabhi Service 8250092165Lucknow Housewife Escorts  by Sexy Bhabhi Service 8250092165
Lucknow Housewife Escorts by Sexy Bhabhi Service 8250092165meghakumariji156
 
CROSS CULTURAL NEGOTIATION BY PANMISEM NS
CROSS CULTURAL NEGOTIATION BY PANMISEM NSCROSS CULTURAL NEGOTIATION BY PANMISEM NS
CROSS CULTURAL NEGOTIATION BY PANMISEM NSpanmisemningshen123
 
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptx
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptxQSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptx
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptxDitasDelaCruz
 
Katrina Personal Brand Project and portfolio 1
Katrina Personal Brand Project and portfolio 1Katrina Personal Brand Project and portfolio 1
Katrina Personal Brand Project and portfolio 1kcpayne
 
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur DubaiUAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubaijaehdlyzca
 
Phases of Negotiation .pptx
 Phases of Negotiation .pptx Phases of Negotiation .pptx
Phases of Negotiation .pptxnandhinijagan9867
 
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizharallensay1
 
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 MonthsSEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 MonthsIndeedSEO
 
Durg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTS
Durg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTSDurg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTS
Durg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTSkajalroy875762
 
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR ESCORTS
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR  ESCORTSJAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR  ESCORTS
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR ESCORTSkajalroy875762
 
Lundin Gold - Q1 2024 Conference Call Presentation (Revised)
Lundin Gold - Q1 2024 Conference Call Presentation (Revised)Lundin Gold - Q1 2024 Conference Call Presentation (Revised)
Lundin Gold - Q1 2024 Conference Call Presentation (Revised)Adnet Communications
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...daisycvs
 
Putting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptxPutting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptxCynthia Clay
 
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service AvailableBerhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Availablepr788182
 

Kürzlich hochgeladen (20)

HomeRoots Pitch Deck | Investor Insights | April 2024
HomeRoots Pitch Deck | Investor Insights | April 2024HomeRoots Pitch Deck | Investor Insights | April 2024
HomeRoots Pitch Deck | Investor Insights | April 2024
 
Organizational Transformation Lead with Culture
Organizational Transformation Lead with CultureOrganizational Transformation Lead with Culture
Organizational Transformation Lead with Culture
 
WheelTug Short Pitch Deck 2024 | Byond Insights
WheelTug Short Pitch Deck 2024 | Byond InsightsWheelTug Short Pitch Deck 2024 | Byond Insights
WheelTug Short Pitch Deck 2024 | Byond Insights
 
Pre Engineered Building Manufacturers Hyderabad.pptx
Pre Engineered  Building Manufacturers Hyderabad.pptxPre Engineered  Building Manufacturers Hyderabad.pptx
Pre Engineered Building Manufacturers Hyderabad.pptx
 
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGParadip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
 
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
 
Lucknow Housewife Escorts by Sexy Bhabhi Service 8250092165
Lucknow Housewife Escorts  by Sexy Bhabhi Service 8250092165Lucknow Housewife Escorts  by Sexy Bhabhi Service 8250092165
Lucknow Housewife Escorts by Sexy Bhabhi Service 8250092165
 
CROSS CULTURAL NEGOTIATION BY PANMISEM NS
CROSS CULTURAL NEGOTIATION BY PANMISEM NSCROSS CULTURAL NEGOTIATION BY PANMISEM NS
CROSS CULTURAL NEGOTIATION BY PANMISEM NS
 
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptx
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptxQSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptx
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptx
 
Katrina Personal Brand Project and portfolio 1
Katrina Personal Brand Project and portfolio 1Katrina Personal Brand Project and portfolio 1
Katrina Personal Brand Project and portfolio 1
 
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur DubaiUAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
 
Phases of Negotiation .pptx
 Phases of Negotiation .pptx Phases of Negotiation .pptx
Phases of Negotiation .pptx
 
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
 
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 MonthsSEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
 
Durg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTS
Durg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTSDurg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTS
Durg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTS
 
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR ESCORTS
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR  ESCORTSJAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR  ESCORTS
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR ESCORTS
 
Lundin Gold - Q1 2024 Conference Call Presentation (Revised)
Lundin Gold - Q1 2024 Conference Call Presentation (Revised)Lundin Gold - Q1 2024 Conference Call Presentation (Revised)
Lundin Gold - Q1 2024 Conference Call Presentation (Revised)
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
 
Putting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptxPutting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptx
 
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service AvailableBerhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
 

Testable Javascript

  • 1. Testable Javascript MARK ETHAN TROSTLERmark@zzo.com @zzoass http://randomgoo.blogspot.com/
  • 2. “If today were the last day of my life, would I want to do what I am about to do today?”
  • 4. Minimize Your Pain •Write Small •Write Simple •Test Early •Test Often
  • 5. Write Small – Write Simple •Isolate code to test •Loosely couple dependencies •Be obvious •Optimize last
  • 6. Test Early – Test Often Test Now
  • 8. How things can go wrong… // Call x.flub with twice z function foo(z) { varx = new X(); // Mmmmmtightly coupled… return x.flub(z*2); } // We want to test if x.flub was called with 14 var back = foo(7); // But only have „back‟ to test! November 9, 2011
  • 9. How can we test only our code? // Call x.flub with twice z function foo(x, z) { return x.flub(z*2); } // Test x.flub got called with 14… varx = new MockX(), foo(x, 7); If (x.called(„flub‟).with(14)) { // a winner!! } November 9, 2011
  • 10. Really see this in constructors… // Ewww – not directly testable function MyObject() { this.x = new X(); } MyObject.Prototpe.foo = function(z) { return this.x.flub(z*2); } var test = new MyObject(), back = test.foo(7) // cannot test what foo() did November 9, 2011
  • 11. Inject It - Constructor // Yea! Testable! function MyObject(x) { this.x = x; } MyObject.Prototpe.foo = function(z) { return this.x.flub(z*2); } varx = new MockX(), test = new MyObject(x); test.foo(7); If (x.called(„flub‟, with(14)) { // We tested only our function! } November 9, 2011
  • 12. Inject It - Setter // Yea! Testable! function MyObject() { } MyObject.prototpe.setX= function(x) { this.x = x; }; MyObject.prototpe.foo = function(z) { return this.x.flub(z*2); }; varx = new MockX(), test = new MyObject(); test.setX(x); test.foo(7); If (x.called(„flub‟, with(14)) { // We tested only our function! } November 9, 2011
  • 13. YUI
  • 14. YUI Explicit Dependencies YUI.add(„myObject‟, function(Y) { // Code you want to test Y.MyObject = function() { this.a = new Y.a(); this.b = new Y.b(); this.c = new Y.c(); }; }, { requires: [ „a‟, „b‟, „c‟ ] }); YUI.use(„myObject‟, function(Y) { new Y.MyObject(); November 9, 2011 });
  • 15. Injecting YUI3 Dependencies?? YUI.add(„myObject‟, function(Y) { //// Code you want to test Y.MyObject = function(a, b, c) { this.a = a; this.b = b; this.c = c; }; }); YUI.use(„myObject‟, „a‟, „b‟, „c‟, function(Y) { // Prod new Y.MyObject(newY.a(), new Y.b(), new Y.c()); }); YUI.use(„myObject‟, „test‟, function(Y) { // Test new Y.MyObject(Y.Mock(), Y.Mock(), Y.Mock()); November 9, 2011 });
  • 16. Isolating Dependencies <script src =“yui3.js”></script> <script src =“a.mock.js”></script> <script src =“b.mock.js”></script> <script src =“c.mock.js”></script> <script src =“myObject.js”></script> <script> YUI.use(„myObject‟, function(Y) { new Y.MyObject(); </script> November 9, 2011
  • 17. Injecting YUI3 Dependencies YUI.add(„myObject‟, function(Y) { //// Code you want to test Y.MyObject = function(a, b, c) { this.a = a || new Y.a(); this.b = b|| new Y.b(); this.c = c|| new Y.c(); }; }, { requires: [„a‟, „b‟, „c‟ ] }); YUI.use(„myObject‟, function(Y) { // Prod new Y.MyObject(); }); YUI.use(„myObject‟, „test‟, function(Y) { // Test new Y.MyObject(Y.Mock(), Y.Mock(), Y.Mock()); }); November 9, 2011
  • 18. Injecting YUI3 Dependencies YUI.add(„myObject‟, function(Y) { //// Code you want to test Y.MyObject = function() { } Y.MyObject.prototype.setX = function(x) { this.x = x; }; }, { requires: [„a‟, „b‟, „c‟ ] }); YUI.use(„myObject‟, function(Y) { // Prod new Y.MyObject(); }); YUI.use(„myObject‟, „test‟, function(Y) { // Test new Y.MyObject().setX(Y.Mock()); }); November 9, 2011
  • 19. Isolating Dependencies YUI({ modules: { a: { fullpath: ‟/a-mock.js' } } }).use('test', ‟myObject', 'console', function( Y) { varobj = new Y.MyObject(); November 9, 2011 });
  • 20. Isolating Dependencies YUI({ filter: mock: { 'searchExp': “.js", 'replaceStr': "-mock.js" } }).use('test', ‟myObject', 'console', function( Y) { varobj = new Y.MyObject(); }); November 9, 2011
  • 22. Mock Object YUI().add(‟a', function(Y) { Y.A= function() { var me = Y.Mock(); Y.Mock.expect(me, { method: ”render", args: [„#toolbar‟] }); return me; } }, '1.0.0' ,{requires:['test']}); November 9, 2011
  • 23. Testing with Mocked Dependencies YUI().add(‟a', function(Y) { Y.A= function() { return Y.Mock(); }; }, '1.0.0' ,{requires:['test']}); YUI().use(„a‟, „test‟, „myObject‟, function(Y) { var a = new Y.A(); Y.Mock.expect(a, { method: ”render", args: [„#toolbar‟] }); new MyObject(a).render(); //// verify a.render(„#toolbar‟) was called }); November 9, 2011
  • 25. „Hidden‟ Dependencies  Private functions are „hidden‟ dependencies  Cannot test by definition!  Make public? Are they part of the public API??  Mock them out?? How??  Refactor private function to be explicit dependencies  Minimize their use – they cannot be tested directly  Treated exactly like any other dependency November 9, 2011
  • 26. Private functions YOU CANNOT TEST THEM! November 9, 2011
  • 27. Don‟t forget browser dependencies! YUI.add(„myObject‟, function(Y) { //// Code you want to test Y.MyObject = function(window) { this.window = window; }; myObject.prototype.fiddle = function(str) { return window.escape(str + „ FOOBIE‟); }; }); YUI.use(„myObject‟, function(Y) { varwinMock = new WindowMock(), myObj = new myObject(winMock); myObj.fiddle(„foobie‟); // Check WindowMock!! } November 9, 2011
  • 28. Recap
  • 29. Explicit Deps Problem: Public dependencies Symptom: Explicitly declared dependencies Cure: • Eliminate tightly coupled code/use injection • Pre-load mock‟ed versions of public dependencies November 9, 2011
  • 30. Private Deps Problem: Private dependencies Symptom: Private methods and functions Cure: • Minimize private dependencies • Make public dependency • Use composition to pull in private stuff November 9, 2011
  • 31. Browser Deps Problem: Browser dependencies Symptom: „window‟ or global scope usage Cure: • Eliminate tightly coupled code/use injection • Pre-load mock‟ed versions of public dependencies November 9, 2011
  • 32. Unit Testing Principles & Practices All about dependency management Identify dependencies and mock them out Do not take your environment for granted November 9, 2011
  • 34. Resources • https://github.com/zzo/JUTE • trostler@yahoo-inc.com • @zzoass • http://randomgoo.blogspot.com/ November 9, 2011

Hinweis der Redaktion

  1. Enjoy writing new code, not debugging oldDebugging, fixing bugs, pulling out hair – debugging other people’s codeAs a dev what is the least favorite part of your day? Debugging / documentationWhat is the hardest part of your day? DebuggingMake life better for yourself and othersI like to code – I like to move forward &amp; get things done – debugging in moving backwardsDebugging can suck – debugging other peoples code does 4 sure
  2. Any kind of test – unit – integration - functional
  3. Get manager-speak out of the wayYou have heard all of this before from industry – from manager – from co-workers - there’s a reason: less pain for you – less pain for you managers – better codeWhy everyone all up in me about these things?You probably already agree it’s a good thingmanagers NEED you to succeedSmall = testableSimple = testable – minimize side effects – side effects harder to test – harder to capture – harder to explainLoosely coupled
  4. Lots of little – no bigPer function – test ONE THING AT A TIMEDo no create - injectIsolate what you want to testMocking out dependenciesCreating causes tight couplingClever comes later – if at all – don’t get cute or too clever – optimize LATERGet clever later
  5. NOWDon’t have to test first – just now
  6. Unit Testing = Isolating &amp; Mocking &amp; dealing with dependenciesYour code has dependencies you need to be aware of
  7. Everyone talks about tightly vs loosely coupled – this is tightly coupled!Basic dependency injection – otherwise tight dependency couplingWhat am I actually testing? This function needed to pass z*2 to X’s flub functionI pass in a mock &amp; an test it did the right thingTight coupling between foo() and X()
  8. Basic dependency injection – static languagesWhat am I actually testing? This function needed to pass z*2 to X’s flub functionI pass in a mock &amp; an test it did the right thing
  9. Basic dependency injectionWe really see this in constructors!!! Sometimes in methodsWhat are you gonna test?? Object X hidden away
  10. Constructor injection –a solution from static languages - We really see this in constructors!!! Sometimes in methodsConstruct objects with their dependencies – which can be goofy – the caller or constructor now needs to know the object’s dependencies!
  11. Setter injection – which to use depends on you &amp; api – prefer constructor – static languagesDepends also if dep is available at construction timeMaybe the setter can only used for testsConstruct objects with their dependencies
  12. Debugging, fixing bugs, pulling out hairAs a dev what is the least favorite part of your day? Debugging / documentationWhat is the hardest part of your day? DebuggingYUI / Javascript lets us be smarter / not have to change our function / constructor signatures
  13. Really really see it in YUI3 codeDeclare YUI3 deps &amp; instantiate themYUI ensure something called a, b, c loaded via mods file or already thereThe load step &amp; then tue ‘use’ stepWe just talked about this being a bad pattern – what can we do?
  14. What about injection???If we inject then our CALLING function needs to know all the deps for myObjectRequires statement now gone!Should we inject???? Is this really what we want?myObject no longer self-contained
  15. Now ready to test myObject!Just pushed deps up to script tags‘YUI3’ injectionIsolating objs using script tagsPre-load the mocks before the ‘real’ objects so YUI3 won’t get them
  16. If we inject then our CALLING function needs to know all the deps for myObjectRequires statement now gone!Declare deps and inject!You might be tempted to do this – hopefully you don’t need to!
  17. Does not have to be constructor injection!!This is better but still adds to our code – makes our code more modular however
  18. A better way – isolate mocks with loaderIf you mock all of your objectsShould mock every object when you make oneOR let YUI create script tags for you using modsUse advanced loader features to inject mocks instead of the ‘real’ thing using ‘filter’ http://randomgoo.blogspot.com/
  19. A better way – isolate mocks with loaderIf you mock all of your objectsShould mock every object when you make oneOR let YUI create script tags for you using modsUse advanced loader features to inject mocks instead of the ‘real’ thing using ‘filter’ http://randomgoo.blogspot.com/
  20. Debugging, fixing bugs, pulling out hairAs a dev what is the least favorite part of your day? Debugging / documentationWhat is the hardest part of your day? Debugging
  21. Mock object – NO DEPS!!Save as toolbar-mock.jsEVERY OBJECT SHOULD HAVE CORRESPONDING MOCK OBJECT!This is for testing DEPENDENCIES OF TOOLBAR NOT for testing toolbar itself!!
  22. However you get it on the page….A is a dependency of MyObjectConstructor injectedMocked DEP NOT OBJ!
  23. Debugging, fixing bugs, pulling out hairAs a dev what is the least favorite part of your day? Debugging / documentationWhat is the hardest part of your day? Debugging
  24. No literally hidden!ONLY test PUBLIC functionsUse the YUI augment or plugin or other way to mix in your private stuff info the object – then they can be tested in isolation
  25. ONLY TEST the PUBLIC parts of YOUR APIMENTION YUI PLUGIN AGGREGATION…Well not directlyInject them or minimize? They are a dependency black boxSince they are only used by your code – if you exercise your code you will exercise themPrivate functions are internal apiIf you got a lotta hairy ones refactor:
  26. Isolate ‘window’ object or make all in a single moduleInject window object or centralize itLets you test in env w/o ‘window or a ‘complete’ window objectKRAPLOAD of stuff in ‘window’!!Want to test that we’re callingwindow.escape with the right thing – maybe can tell from return value – maybe notEsp. stuff like local storage or xmlhttprequest or websockets
  27. Debugging, fixing bugs, pulling out hairAs a dev what is the least favorite part of your day? Debugging / documentationWhat is the hardest part of your day? Debugging
  28. Unit testing is testing functions in isolationBut dependencies – which everything has – can be pain pointsHow about zero dependencies???Ride JS to a conclutionYUI3 is a service locatorMORE smaller modules!! Use YUI ‘use’ &amp; composition to build them!
  29. Can’t test!
  30. Unit testing is testing functions in isolationBut dependencies – which everything has – can be pain pointsHow about zero dependencies???Ride JS to a conclutionYUI3 is a service locator
  31. All about dep managementIdentify deps &amp; deal with themDo not require/assume global variables – your module is a black boxAllow for headless tests
  32. Debugging, fixing bugs, pulling out hairAs a dev what is the least favorite part of your day? Debugging / documentationWhat is the hardest part of your day? DebuggingWorst part debugging your codeEven worser part debugging someone else’s code – don’t be that someone else!Make life easier and better for yourself and your co-workers by having tests in place – writing simple &amp; obvious code = testable code
  33. All about dep managementIdentify deps &amp; deal with themDo not require/assume global variables – your module is a black box