Unit Testing Stencil Components - Ionic Blog

文章推薦指數: 80 %
投票人數:10人

We have added a unit testing framework to Stencil. Stencil is a tool for building modern Web Components. Stencil combines some of the best ... Appflow GettingStarted Docs Platform Enterprise Studio Appflow Pricing Resources Documentation ResourceCenter Community Blog Solutions OfflineStorage BiometricSignin UserAuthentication GetHelp Support Advisory Training Login Signup Products GettingStarted Documentation Login Signup Platform Products Framework Studio Appflow Native Solutions Integrations OfflineStorage BiometricSignIn UserAuthentication ProgressiveWebApps CrossPlatformApps GetHelp Support Advisory Training Developers Docs Installation UIComponents Native CLI AppflowDocs Quickstart NativeBuilds LiveUpdating Automation OpenSource Framework Stencil Capacitor Resources ResourceCenter Articles&Whitepapers CaseStudies Webinars Videos Podcast CommunityHub Forum Slack Twitter YouTube GitHub Courses EliteIonic IonicAcademy IonicCLI PWAswithIonic Seeall... FantasticMobileDevTools,andWheretoFindThem!… Pricing Enterprise Blog /UnitTestingStencilComponents GettheNewsletter Togglenavigation Share UnitTestingStencilComponents By Ken Sodemann on November17,2017 in testingTools WehaveaddedaunittestingframeworktoStencil.StencilisatoolforbuildingmodernWebComponents.Stencilcombinessomeofthebestfeaturesfromtraditionalframeworks,butoutputs100%standards-compliantCustomElements,partoftheWebComponentspec. Thegoalswehadwhenaddingthetestingframeworkweresimple:makeiteasytounderstand,andkeeptheAPIassmallaspossible.Asaresultofthis,thetestingAPIhasatotaloftwomethods:render()andflush(). render()–TherendermethodtakesanobjectcontainingalistofcomponentsthattheStencilcompilerneedstoknowaboutandanHTMLstring.Itreturnstherenderedelement. flush()–Theflushmethodtakesanelementandcausesittorerender.Thisistypicallydoneafterpropertiesontheelementarechanged. GettingStarted InordertogetstartedwithunittestingStencilcomponents,clonetheStencilComponentStarterandrunnpminstall.Toruntheunittests,useoneofthefollowingcommands: npmtest–performsasinglerunoftheunittests npmruntest.watch–runstheunittestsandwatchesforchangestothesource,rerunningtheunittestwitheachsavedchange Ineithercase,Jestisusedtoruntheunittests. ApplicationSetup Inordertoperformunittestsonthecomponentsintheaproject,someminimalsetupisrequiredintheproject’spackage.jsonfile.Thetestingpackagesneedtobeinstalledasdevelopmentdependencies,thenpmscriptsthatrunthetestsneedtobedefined,andJestneedstobeconfiguredtocompilethesourcesandthetestsproperly. Theonlypackagesrequiredinordertorunthetestsarejestand@types/jest: "devDependencies":{ ... "@types/jest":"^21.1.1", "jest":"^21.2.1" }, Thetwotestingrelatednpmscriptsaretestandtest.watch. "scripts":{ ... "test":"jest--no-cache", "test.watch":"jest--watch--no-cache" }, ThejestsetupsectionspecifiesthemoduleFileExtensions,testRegex,andtransform.TheonlypartofthesetupthatisspecifictoStencilisthetransformsection.StencilprovidesapreprocessorscriptthatusestheStencilcompilertobuildthesourceandtestfiles. "jest":{ "transform":{ "^.+\\.(ts|tsx)$":"/node_modules/@stencil/core/testing/jest.preprocessor.js" }, "testRegex":"(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$", "moduleFileExtensions":[ "ts", "tsx", "js", "json", "jsx" ] } Thatisallofthesetupthatisrequiredinordertoruntheunittests.SincethishasalreadybeendoneintheStencilComponentStarter,ifyouareusingthatasastartingpointforyourprojectyoushouldnotneedtodoanyextrasetup. TheTestFile TheStencilComponentStartercontainsonetestfile:src/components/my-name/my-name.spec.ts.Thisfilecontainsonetestthatjustensuresthecomponentcanbebuilt,andagroupofteststhatverifytherenderingofthecomponent. TestingtheComponentClass Thefirsttestensuresthatthecomponentclasscanbebuilt. it('shouldbuild',()=>{ expect(newMyName()).toBeTruthy(); }); Ifthecomponenthadmethodsdefinedonit,thesametechniquecouldbeusedtoobtainanobjecttousetotestthosemethods.Forexample,ifMyNamecontainedamethodformat()thatreturnedaformattedname,youcouldtestitassuch: it('shouldbuild',()=>{ constmyName=newMyName(); myName.first='Peter' myName.last='Parker'; expect(myName).toEqual('Parker,Peter'); }); TestingtheComponentRendering Testscanalsorenderthecomponentsothestructureofthecomponentcanbetested.Thisisaccomplishedviatwofunctions:render()andflush().Therender()functiontakesaconfigurationobjectconsistingofalistofcomponentsandandHTMLsnippet,returninganHTMLElement.Theflush()functiontakesanelementandapplieschangestoit.Bothfunctionsperformtheirtasksasynchronously. SincebothofthesefunctionsworkwithHTMLelements,thestandardHTMLElementAPIisusedtomanipulateandquerythestructureoftheelement. describe('rendering',()=>{ letelement; beforeEach(async()=>{ element=awaitrender({ components:[MyName], html:'' }); }); ... it('shouldworkwithbothafirstandalistname',async()=>{ element.first='Peter' element.last='Parker'; awaitflush(element); expect(element.textContent).toEqual('Hello,mynameisPeterParker(4)'); }); }); NextSteps InthisarticleweexplainedtheStencilunittestingframeworkAPI,consistingoftwofunctions:render()andflush().Weshowedtheadditionsrequiredtothepackage.jsonfileinordertoallowunittesting.FinallywewalkedthroughthesmallsampletestthatisincludedintheStencilComponentStarter,andhighlightedsomeofthefunctionality. Inafuturepost,Iwillwalkthroughusingthistestalongwithsomebasictest-drivendevelopmentinordertoextendourcomponenttomeetourcustomer’snewrequirements. SignupfortheIonicNewslettertogetthelatestnewsandupdates!



請為這篇文章評分?