Testto

eaccelerator  时间:2021-02-05  阅读:()
CopyrightIBMCorporation2015TrademarksMasteringMEAN:TestingtheMEANstackPage1of12MasteringMEAN:TestingtheMEANstackScottDavisJuly28,2015Takeawalkthroughthesmallpieces,looselyjoinedoftheMEANstack'stestinginfrastructure.
Noapplication,MEANorotherwise,isreadyforproductionwithoutpassingarigorous,comprehensivetestsuite.
SeehowtouseKarma,Mocha,Jasmine,andistanbul—withthehelpofPhantomJS—totesttheUGLIapp.
ViewmorecontentinthisseriesTheUserGroupListandInformation(UGLI)apphascomealongwaysinceyoustartedit.
You'restoringlocaldataintheapplicationandpullinginremotedatathroughRESTfulwebservices.
Theapplicationsportsamobile-readyresponsivewebdesign,andit'ssemanticallymarkeduptomakethemostofsearchengineoptimization(SEO).
Forauthentication,userscaneithercreatealocal,dedicatedaccountor(viaOAuth)reuseanexistingaccountstoredelsewhere.
Butyouwouldn'tfeelcomfortableputtingtheUGLIappintoproductionwithoutasolidtestingsuiteasyoursafetynet,wouldyouOfcoursenot.
Thatwouldbeprofessionallyirresponsible.
IagreewithNealFord(authorandinternationalspeaker),whocallstesting"theengineeringrigorofsoftwaredevelopment.
"WheneverIstartanengagementwithnewclients,Ilookattheirtestsuitebeforeanythingelse—eventheirdesigndocuments.
Thequality,quantity,andcomprehensivenessoftheirtestshasadirectcorrelationtothematurityoftheirsoftwaredevelopmentprocess.
Ahealthy,activelymaintainedtestsuiteisthebellwetherofaproject'soverallhealth.
Similarly,anyframeworkthatplacesapremiumontestabilitymovestothetopofmylist.
AngularJSwaswrittenbytesters,andI'mhard-pressedtothinkofanothermodernwebframeworkthat'seasiertotest.
TheMEAN.
JSstackextendstheout-of-the-boxtestabilitytoincludetestingofserver-sidelogic.
"AngularJSwaswrittenbytesters,andI'mhard-pressedtothinkofanothermodernwebframeworkthat'seasiertotest.
"Atthebeginningofthisseries,IwalkedyouthroughthebasicbuildingblocksoftheMEANstack—thesmallpieces,looselyjoinedthatmakeuptheproductioncomponentsofyourapp.
Nowit'stimetodothesameforthevariousframeworksandlibrariesyou'llusetotestyourappandmakeitproduction-ready.
I'llintroduceyoutoKarma:apluggabletestrunnerthatmakesittrivialtoruntestswritteninanytestingframeworkacrossanynumberofrealwebbrowsers(includingdeveloperWorksibm.
com/developerWorks/MasteringMEAN:TestingtheMEANstackPage2of12smartphones,tablets,andsmartTVs)andreturntheresultsinawidevarietyofformats.
Alongtheway,you'lluseJasmineforclient-sidetesting,Mochaforserver-sidetesting,andistanbulforcodecoverage.
RunningyourtestsBecauseyou'vebeenusingtheYeomangeneratorthatshipsstandardwiththeMEAN.
JSframework,youalreadyhaveseveralgeneratedtestsinplace.
Typegrunttesttorunthem.
YoushouldseeresultssimilartothoseinListing1.
Listing1.
Runningthegeneratedtests$grunttestRunning"env:test"(env)taskRunning"mochaTest:src"(mochaTest)taskApplicationloadedusingthe"test"environmentconfigurationRunning"karma:unit"(karma)taskINFO[karma]:Karmav0.
12.
31serverstartedathttp://localhost:9876/INFO[launcher]:StartingbrowserPhantomJSINFO[PhantomJS1.
9.
8(MacOSX)]:Connectedonsocket6zkU-H6qx_m2J6lY4zJ8withid51669923PhantomJS1.
9.
8(MacOSX):Executed18of18SUCCESS(0.
016secs/0.
093secs)Done,withouterrors.
Don'tbeconcernedifyouhaveerrorsorwarnings;thetestsarescaffoldedouttomatchthemodelsandcontrollersasthey'reinitiallyimplemented.
Ifyou'vebeenmakingchangestothecodeundertest(CUT)andnotupdatingthecorrespondingtests,youcanexpecterrors.
I'mthrilledeverytimeaunittestfails.
Unittestsarethecircuitbreakersofyourcodebase.
Inyourhouse,youputcircuitbreakersinbetweenthepowergridandyourexpensivepersonalelectronics.
Thatwaywhenapotentiallydamagingpowersurgecomesinoverthewire,youstandtolosea35-centcircuitbreakerinsteadofa$3,500laptop.
Similarly,everybreakingunittestisanerrorthatyouseeandyourusersdon't.
Takeamomenttofixyourbrokentestsifyoucan.
Acommonsourceoferrorsisatest'srelianceondeletedorchangedfieldnames.
Theserver-sidetestsareinapp/tests.
Theclient-sidetestsarestoredinthetestdirectoryofeachpublic/module.
Ifyoucan'timmediatelyseethesourceoftheerrorinyourtest,don'tdeletethetest;simplymoveitoutofthedirectorytreetemporarily.
Nowthatyoucanmakeacleantestrun,it'stimetodeconstructtheprocess.
UnderstandingtheGrunttesttaskAsyoutypedgrunttest,Ihopethatyouaskedyourself,"Hmm,IwonderhowGruntisrunningthosetests.
"Grunt,asyouknow,runsyourbuildscript.
Opengruntfile.
jsinyourtexteditorandscrollallthewaytothebottomofthefile.
Youcanseethetesttaskbeingregistered://Testtask.
grunt.
registerTask('test',['env:test','mochaTest','karma:unit']);ibm.
com/developerWorks/developerWorksMasteringMEAN:TestingtheMEANstackPage3of12Thefirstargumentofgrunt.
registerTaskisthenameofthetask—inthiscase,test.
Thenextargumentisanarrayofdependenttasks.
Thetesttaskfirstsetsupvaluesspecifictothetestenvironment,thenrunsalloftheserver-sidetestswritteninMocha,andfinallykicksofftheclient-sidetestsviaKarma.
Scrollupabitingruntfile.
jsuntilyoufindtheenvtask:env:{test:{NODE_ENV:'test'}},ThistaskdoeslittlemorethansettheNODE_ENVvariabletotest.
RecallthatthisvariablehelpsGruntdeterminewhichenvironment-specificsettings—inthiscase,config/env/test.
js—tomergewiththecommonsettingsinconfig/env/all.
js.
Ifyoulookatconfig/env/test.
jsinatexteditor(asshowninListing2),you'llseeacustomMongoDBconnectionstring,alongwithhooksforallofthePassportsettingsforvariousOAuthproviders:Listing2.
config/env/test.
js'usestrict';module.
exports={db:'mongodb://localhost/test-test',port:3001,app:{title:'Test-TestEnvironment'},facebook:{clientID:process.
env.
FACEBOOK_ID||'APP_ID',clientSecret:process.
env.
FACEBOOK_SECRET||'APP_SECRET',callbackURL:'http://localhost:3000/auth/facebook/callback'},google:{clientID:process.
env.
GOOGLE_ID||'APP_ID',clientSecret:process.
env.
GOOGLE_SECRET||'APP_SECRET',callbackURL:'http://localhost:3000/auth/google/callback'},//snip};ThissectionwouldbeanidealplaceforyoutopointPassporttoamockimplementationoftheMeetupauthenticationstrategy.
Thatway,youdon'tneedtorelyonhavingactualuserssetupandmakeactualOAuthrequeststoMeetup.
comduringyourtestrun.
Afterthetestenvironmentisconfigured,Gruntrunsallofyourserver-sidetestswritteninMocha.
Here'sthemochaTesttask:developerWorksibm.
com/developerWorks/MasteringMEAN:TestingtheMEANstackPage4of12mochaTest:{src:watchFiles.
mochaTests,options:{reporter:'spec',require:'server.
js'}},KnobsanddialsFormoreinformationontheknobsanddialsyoucantwistwhenrunningyourMochatests,seetheplugindocumentationforgrunt-mocha-test.
Whyaretheserver-sidetestswritteninMochainsteadofJasmineMocha'smaturity,extensibility,andpluginsmakeitoneofmyfavoritetestingframeworks.
MochaisastrongchoicefortestingthingslikeExpressroutes,controllers,andMongoDBinteraction.
AlthoughMochacaneasilyruntestsbothinNode.
jsandin-browser,theAngularJSteamprefersJasmineforin-browsertesting.
Jasmineismoreoptimizedforclient-sidetesting,sotheMEAN.
JSdeveloperstookabest-of-breedapproachandchoseastrongserver-sidetestingframeworktotesttheserverside,andastrongclient-sidetestingframeworktotesttheclientsideofthings.
Youshouldfeelcomfortableswappingouteitherorbothframeworksforthetestingtoolsofyourchoice.
Becauseserver-sidetestsare(bydefinition)notrunin-browser,theMochatestsarenotkickedoffbyKarma.
TheJasminetests—thefinalpartoftheGrunttestdependencies—aretriggeredbythekarmatask:karma:{unit:{configFile:'karma.
conf.
js'}}BeforeImoveontodeconstructingthekarma.
conf.
jsfile,openpackage.
jsoninatexteditor.
Inadditiontotheruntimemoduleslistedinthedependenciesblock,youcanseeseveralbuild-timedependencieslistedinthedevDependencies(shortfordeveloperdependencies)block.
ThisblockisspecificallywheretheGruntpluginsrelatedtoMochaandKarmaaredeclaredandinstalledwhenyoutypenpminstall:"devDependencies":{"grunt-env":"~0.
4.
1","grunt-mocha-test":"~0.
10.
0","grunt-karma":"~0.
8.
2","load-grunt-tasks":"~0.
4.
0",//snip}IntroducingKarmaKarmaistheonlytestrunnerIknowofthatisbackedupbyamaster'sthesis.
AmoresuccinctversionofthethinkingbehindKarmaistheproject'smissionstatement:Thingsshouldbesimple.
Webelieveintestingandsowewanttomakeitassimpleaspossible.
ibm.
com/developerWorks/developerWorksMasteringMEAN:TestingtheMEANstackPage5of12Andsimpleitis.
Karmaallowsyoutowriteyourtestsintheframeworkofyourchoice.
Whetheryoupreferthetest-driven-development(TDD)styleofQUnitorthebehavior-driven-development(BDD)styleofJasmine,Karmawillhappilyruntestswritteninanystyle.
(Karmaalsooffersfirst-classsupportforMochaifyouwouldprefertouseasingletestingframeworkforwritingbothserver-andclient-sidetests.
)Seasonedwebdevelopersknowhowimportantitistotesttheirappsacrossawidevarietyofbrowsers.
ThecoreJavaScriptlanguageisremarkablyconsistentacrossbrowsers,butDocumentObjectModel(DOM)manipulationandwaystomakeAjaxrequestsarefarfromstandardized.
MainstreamlibrarieslikejQueryandAngularJSdoagreatjobofpolyfillingoverbrowserincompatibilities,butthatshouldn'tlullyouintoafalsesenseofcomplacency.
Onetestisworthathousandopinions,andhavingproofthatyourappworksasintendedinaspecificbrowserisfarpreferabletosimplyassumingthatitwill.
Karmaoffersseveralpluginsthatyoucanusetolauncharealbrowserondemand,runthefulltestsuite,andthenshutdownthebrowseruponcompletion.
Thatcapabilityisconvenientforrunningthetestslocallyinthebrowserofyourchoice,butitcanbelimitingifthetestsarebeingkickedoffbyaheadlesscontinuousintegrationserversuchasJenkins,Hudson,orStrider.
Thankfully,youcanstandupalong-runningKarmaserverandcapturebrowsersonremotedevices.
CapturingabrowserisassimpleasvisitingtheURLofyourKarmaserverinthebrowser.
IfthebrowsersupportsWebSockets(caniuse.
comshowssupportineverymainstream,modernbrowser),theKarmaserverwillmaintainalong-running,durableconnectionwiththedevice.
Asnewtestsareaddedtothesuite,theKarmaserverwillserializethemacrossthewiretotheremotebrowser,runthem,andreturntheresults.
Butwhatgoodisrunningthetestsuiteifyoucan'tquantifytheresultsKarmaofferspluginsforseveraldifferentreporters.
Areportercanbeassimpleassomethingthatprintsoutadotonthecommandlineforeachpassingtest.
OrareportercanyieldfullyformattedHTML,oremitrawJUnit-compatibleXMLthatcanbetransformedintotheoutputofyourchoice.
Testingframeworks,browserlaunchers,andresultsreportersarealldefinedinthekarma.
conf.
jsfile.
Understandingkarma.
conf.
jsOpenkarma.
conf.
jsinatexteditor,asshowninListing3.
Inthefile,you'llfindclearlylabeledsettingsforframeworks,files,reporters,andbrowsers.
Listing3.
karma.
conf.
js'usestrict';/***Moduledependencies.
*/varapplicationConfiguration=require('.
/config/config');//Karmaconfigurationmodule.
exports=function(config){config.
set({developerWorksibm.
com/developerWorks/MasteringMEAN:TestingtheMEANstackPage6of12//Frameworkstouseframeworks:['jasmine'],//Listoffiles/patternstoloadinthebrowserfiles:applicationConfiguration.
assets.
lib.
js.
concat(applicationConfiguration.
assets.
js,applicationConfiguration.
assets.
tests),//Testresultsreportertouse//Possiblevalues:'dots','progress','junit','growl','coverage'//reporters:['progress'],reporters:['progress'],//Webserverportport:9876,//Enable/disablecolorsintheoutput(reportersandlogs)colors:true,//Leveloflogging//Possiblevalues:config.
LOG_DISABLE||config.
LOG_ERROR||config.
LOG_WARN||config.
LOG_INFO||config.
LOG_DEBUGlogLevel:config.
LOG_INFO,//Enable/disablewatchingfileandexecutingtestswheneveranyfilechangesautoWatch:true,//Startthesebrowsers,currentlyavailable://-Chrome//-ChromeCanary//-Firefox//-Opera//-Safari(onlyMac)//-PhantomJS//-IE(onlyWindows)browsers:['PhantomJS'],//Ifbrowserdoesnotcaptureingiventimeout[ms],killitcaptureTimeout:60000,//ContinuousIntegrationmode//Iftrue,itcapturebrowsers,runtestsandexitsingleRun:true});};Referbacktopackage.
json.
InthatfileyoucanfindcorrespondingentriesinthedevDependenciesblockforthevariousKarmaplugins:"devDependencies":{//snip"karma":"~0.
12.
0","karma-jasmine":"~0.
2.
1","karma-coverage":"~0.
2.
0","karma-chrome-launcher":"~0.
1.
2","karma-firefox-launcher":"~0.
1.
3","karma-phantomjs-launcher":"~0.
1.
2"}Becauseallofthescaffoldedclient-sidetestsarewritteninJasmine,Irecommendleavingtheframeworksarrayasitstands.
Butasyou'llseelaterinthissection,youcanfeelcomfortableaddingandremovingbrowsersatwill.
ibm.
com/developerWorks/developerWorksMasteringMEAN:TestingtheMEANstackPage7of12IntroducingPhantomJSIfyou'reawebdeveloperbutaren'tfamiliarwiththePhantomJSbrowser,you'reinforatreat.
PhantomJSisoneofawebtester'sbestfriends.
It'seasytobetrickedintothinkingofwebbrowsersasmonolithicapplicationsidentifiedbyfamiliarbrandnames:Firefox,Chrome,Safari,Opera,andInternetExplorer.
Thosebrandnamesaremerelyaconvenientwaytodescribeaspecificcollectionoftechnologiesthatincludearenderingengine(forHTMLandCSS),ascriptingengine(forJavaScript),andapluginsubsystem.
"Nowthatyou'reaseasonedMEANdeveloper,you'realreadyintimatelyfamiliarwithpluckingcomponentsoutofabrowserandrunningthemheadlessly.
Youshouldfeelrightathomerunningaheadlessrenderkitfortesting.
"Onceyourecognizebrowsersasaloosecollectionofrenderingkitsandscriptingengines,awholenewlevelofunderstandingopensup.
Forinstance,theNetscapeNavigatorbrowserhada90+percentmarketsharewhenversion2.
0wasreleasedinthemid1990s.
IEtookoverthatmarketleadjustafewyearslater.
Butinrecentyears,arenderkit—WebKit—ratherthanabrowserenjoysamajoritymarketshare.
That'sbecauseuntilrecently(seetheWebKit,meetBlinksidebar),WebKitpoweredSafari,MobileSafari,Chrome,theAndroidbrowser,theBlackBerrybrowser,Kindledevices,PlayStation,SamsungsmartTVs,LGsmartTVs,PanasonicsmartTVs,andmore.
Eventhoughtheseapplicationsanddeviceswereallassembledbydifferentcompaniesandprojects,theyshareacommonrenderkitfordisplayingHTMLandstylingitwithCSS.
WebKit,meetBlinkGooglemadenewsin2013withtheannouncementthatitwasforkingtheWebKitprojectandcreatingaseparaterenderkitnamedBlink.
Soonafter,OperaannouncedthatitwouldstopdevelopingitscustomrenderkitandadoptBlinkinstead.
(Thislistshowstheunderlyingrenderkitforallmajorbrowsers.
)Apple,whichoriginallyforkedWebKitfromtheKHTMLrenderingenginein2005,continuestoactivelydevelopandmaintaintheproject.
(SeetheWebKitentryinWikipediaformoreinformation.
)So,whatdoesthishavetodowithPhantomJSThePhantomJSwebsitetellsus:PhantomJSisaheadlessWebKitscriptablewithaJavaScriptAPI.
Aheadlessservicedoesn'trequireamonitororaGUI.
Thatsoundsperfectforrunningbrowser-basedunittestsonamonitorlesscontinuousintegrationserver,doesn'tit(TheSlimerJSprojectoffersasimilarcapability:runningaheadlessGeckorenderkittotestthepagerenderingthatoccursintheFirefoxbrowser.
)Nowthatyou'reaseasonedMEANdeveloper,you'realreadyintimatelyfamiliarwithpluckingcomponentsoutofabrowserandrunningthemheadlessly:Node.
jsisGoogleChrome'sscriptingengine(V8)runningheadlessly.
Youshouldfeelrightathomerunningaheadlessrenderkitfortesting.
developerWorksibm.
com/developerWorks/MasteringMEAN:TestingtheMEANstackPage8of12Lookingbackatkarma.
conf.
js,youcanseethatPhantomJSisinthebrowsersarray.
NowyouunderstandhowalloftheJasmineclient-sidetestscouldrunandpassinabrowserwithoutyouseeingaGUIlaunch.
ConfiguringKarmatolaunchadditionalbrowsersKarmaofferslaunchersforallmajorbrowsers.
IfyoulookbackatthedevDependenciesblockofpackage.
json,youcanseethatlaunchersarealreadyinstalledforFirefoxandChrome.
Ifyouhavethosebrowsersinstalledonyourcomputer,addthemtothebrowsersarrayinkarma.
conf.
jsandtypegrunttesttorunyourtestsuiteinthenewlyaddedbrowsers.
Iencourageyoutovisitthenpmwebsiteandsearchforkarmalaunchertoseealistofallsupportedbrowsers.
Youinstalleachlauncherandaddittopackage.
jsonbytypingnpminstallkarma-xxx-launcher--save-dev.
Oncethelauncherisinstalled,addittothebrowsersarrayinkarma.
conf.
jsandrerunyourtests.
Capturingbrowsersthatcan'tbelaunchedKarmalaunchersaretypicallyusedtolaunchbrowsersthatareco-locatedonthesamecomputer.
RecallthatKarmacanbeusedtoruntestsonremotebrowsersalso—thinksmartphones,tablets,andsmartTVs.
AnybrowserthatsupportsWebSocketscanbecapturedbyKarmaandusedasatesttarget.
Tocapturearemotebrowser,youmustfirstleavetheKarmaserverupandrunningbetweentestruns.
ToleavetheKarmaserverrunningpermanently,changethesingleRunvaluetofalseinkarma.
conf.
js://ContinuousIntegrationmode//Iftrue,itcapturebrowsers,runtestsandexitsingleRun:trueIfyourebooteithertheKarmaserveroranyofthecapturedbrowsers,they'lltrytoreconnectandrerunallofthetests.
NowthattheKarmaserverisupandrunning,visititinaremotebrowserattheURLhttp://your.
server.
ip.
address:9876.
That'sallittakestocaptureanonlaunchablebrowserusingKarma.
AddingadditionalKarmareportersNowthatyou'recomfortableaddingadditionaltestsandbrowsers,consideraddingadditionalreporterstocaptureanddisplaytheresultsofthetests.
Tostart,addthedotsreportertothereportersarrayinkarma.
conf.
js.
Thenexttimeyoutypegrunttest,you'llseeaseriesofdotsflyacrossyourscreen—oneforeverypassingtest.
Thedotsarecutebutephemeral.
Howwillyouknowhowmanytestspassedunlessyou'rewatchingthescreenastheyrunPerhapsinstallingareporterthat'sabitmoredurableisinorder.
ibm.
com/developerWorks/developerWorksMasteringMEAN:TestingtheMEANstackPage9of12Thekarma-html-reporterismostlikelywhatyou'relookingfor.
AstheexampleinFigure1shows,yougetdetailedverbalresultsforeachtest,nicelyformattedinHTML.
Figure1.
Reportgeneratedbykarma-html-reporterToinstallkarma-html-reporter,typenpminstallkarma-html-reporter--save-dev.
Thentoconfigureit,editkarma.
conf.
jslikeso:reporters:['progress','html'],htmlReporter:{outputDir:'karma_html'},Seethekarma-html-reporterpackagedetailsforthefullsetofconfigurationoptions.
IfyouwouldpreferrawXMLoutputinsteadofpolishedHTMLoutput,considerinstallingthekarma-junit-reporter.
Toinstallit,typenpminstallkarma-junit-reporter--save-dev.
Thenconfigureitinkarma.
conf.
jsasshownattheprojectsite.
Youtypedkarmalauncheratthenpmwebsitetosearchforadditionallaunchers.
YoushouldfeelequallycomfortabletypingkarmareportertofindadditionalKarmareporters.
ShowingcodecoveragewithKarmaandistanbulNotestinginfrastructureiscompletewithoutshowingtestcodecoverage.
Thepreviousreportsonlyshowedyoutheteststhatpassedandfailed—theydidn'tshowyoutheteststhatyouforgotdeveloperWorksibm.
com/developerWorks/MasteringMEAN:TestingtheMEANstackPage10of12towrite.
Agoodcode-coveragetoolshowsyouline-by-linewhichpartsofyourcodebasewerevisitedbyunittests,andmoreimportant,whichlinesofcodehaven'tbeenvisitedbyaunittestyet.
Ifyouinstallthekarma-coverageplugin(whichusestheistanbullibrary)bytypingnpminstallkarma-coverage--save-devandconfigureitbasedontheinstructions,you'llgetasetofbeautifulreportsthatdisplayeverylineofcodeinyourapplication,asinFigure2.
Figure2.
CoveragereportThegreenlineshavebeentouchedbyaunittest,andtheredlinesarethelineswaitingforafutureunittest.
MockingdependenciesAhallmarkofwell-writtenunittestsistheirindependence.
TheyshouldneverrelyonactualdatabasesormakeactualHTTPcallstolivewebservices.
Thankfully,mockingoutthesedependenciesisatime-honoredwayofrunningyourtests.
InsteadofmakingactualAjaxcallsinyourclient-sideJasminetests,considerusingthe$httpBackendmockserviceincludedwithAngularJS.
ibm.
com/developerWorks/developerWorksMasteringMEAN:TestingtheMEANstackPage11of12InsteadofrelyingonanactualMongoDBdatabasefortesting,considerusingMockgoose—apurein-memorydrop-inreplacementforMongoose(andMongoDB)writtenexpresslyfortestingpurposes.
Runningend-to-endtestswithProtractor.
jsUptothispoint,you'vebeenrunningunittests.
Unittests—bydefinition—areteststhatdon'trelyonaGUI.
Unittestsareforthenon-UIpartsofyourcodebase.
Butwhatabouttestingallofthetypingandbuttonclickingthattypicaluserswillperformwhenthey'reusingyourappTotestthattypeofbehavior,youcaninstallProtractor.
js.
TheProtractorhomepagehasafullsetofinstructionsandexamples.
Here'stheshortversion:typenpminstallprotractor--save-devtoinstallthelibrary.
Next,youwriteJasmineteststhatvisitspecificURLsandinteractwithspecificcomponentsonthepage.
Listing4showsanexampleofaProtractortestfromtheproject'shomepage.
Listing4.
AProtractortestdescribe('angularjshomepagetodolist',function(){it('shouldaddatodo',function(){browser.
get('http://www.
angularjs.
org');element(by.
model('todoText')).
sendKeys('writeaprotractortest');element(by.
css('[value="add"]')).
click();vartodoList=element.
all(by.
repeater('todointodos'));expect(todoList.
count()).
toEqual(3);expect(todoList.
get(2).
getText()).
toEqual('writeaprotractortest');});});Asyou'veprobablysurmised,thistestvisitstheAngularJShomepage,findsthetodoTextelement,typesinateststring,andclickstheaddbutton.
Thenitrunsaseriesofassertionstoensurethattheexpectedvaluesappear.
ConclusionAsIsaidearlier,andasIoftensay,onetestisworthathousandopinions.
Butcheekyrejoindersworkonlyifyoucanbackthemupwithsolidsoftwarepractices.
Ifyouputthelessonslearnedfromthisarticleintoplace,you'llbewellonyourwaytowardthe"engineeringrigor"requiredtobeapartofthisfast-paced,ever-changingsoftwareecosystem.
developerWorksibm.
com/developerWorks/MasteringMEAN:TestingtheMEANstackPage12of12RelatedtopicsAngularJSunittesting:CheckouttheunittestingsectionoftheAngularJSDeveloperGuide.
MEAN.
JStestingdocumentation:TakealookatthetestingsectionsintheMEAN.
JSdocs.
Karma:FindoutallaboutKarmaandseetheavailablepluginsforKarmaattheprojectsite.
PhantomJS:Learnmoreaboutthisscriptable,headlessbrowser.
Mocha:VisittheMochahomepagefordocumentationandexamples.
Jasmine:CheckouttheJasminedocumentation.
CopyrightIBMCorporation2015(www.
ibm.
com/legal/copytrade.
shtml)Trademarks(www.
ibm.
com/developerworks/ibm/trademarks/)

香港 E5-2650 16G 10M 900元首月 美国 E5-2660 V2 16G 100M 688元/月 华纳云

华纳云双11钜惠出海:CN2海外物理服务器终身价688元/月,香港/美国机房,免费送20G DDos防御,50M CN2或100M国际带宽可选,(文内附带测评)华纳云作为一家专业的全球数据中心基础服务提供商,总部在香港,拥有香港政府颁发的商业登记证明,APNIC 和 ARIN 会员单位。主营香港服务器、美国服务器、香港/美国OpenStack云服务器、香港高防物理服务器、美国高防服务器、香港高防I...

3元/首月香港便宜vps究竟是什么货。

便宜的香港vps多少钱?现在国外VPS主机的价格已经很便宜了,美国VPS主机最低一个月只要十几元,但同样免备案的香港VPS价格贵不贵呢?或者说便宜的香港VPS多少钱?香港vps主机价格要比美国机房的贵一些,但比国内的又便宜不少,所以目前情况是同等配置下,美国VPS比香港的便宜,香港VPS比国内(指大陆地区)的便宜。目前,最便宜香港vps低至3元/首月、18元/月起,今天云服务器网(www.yunt...

选择Vultr VPS主机不支持支付宝付款的解决方案

在刚才更新Vultr 新年福利文章的时候突然想到前几天有网友问到自己有在Vultr 注册账户的时候无法用支付宝付款的问题,当时有帮助他给予解决,这里正好顺带一并介绍整理出来。毕竟对于来说,虽然使用的服务器不多,但是至少是见过世面的,大大小小商家的一些特性特征还是比较清楚的。在这篇文章中,和大家分享如果我们有在Vultr新注册账户或者充值购买云服务器的时候,不支持支付宝付款的原因。毕竟我们是知道的,...

eaccelerator为你推荐
关于上报下学期所需教学软件的通知中断fastreport2usergoogleipad如何上网IPAD4怎样上网?勒索病毒win7补丁求问win7 64位旗舰版怎么预防勒索病毒ipadwifiIpad怎么用移动无线上网iphonewifi苹果手机怎么扫二维码连wifiwin7如何关闭445端口如何关闭445端口,禁用smb协议360chrome360的chrome浏览器进程有点多哦???icloudiphone苹果手机显示"已停用,连接itunes"是什么意思
阿里云os photonvps site5 yardvps 电影服务器 java主机 cdn服务器 搬瓦工官网 iisphpmysql 512m ibrs 免费全能空间 本网站服务器在美国 e蜗牛 阿里校园 微软服务器操作系统 个人免费主页 彩虹云 双线asp空间 免费个人主页 更多