Unit Testing - Stencil.js

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

Stencil makes it easy to unit test components and app utility functions using Jest. Unit tests validate the code in isolation. Well written tests are fast, ... DocsResourcesBlogEnterpriseEnglish日本語IntroductionOverviewGoalsandObjectivesGettingStartedMyFirstComponentComponentsAPIComponentLifecycleMethodsPropertiesInternalStateReactiveDataUsingJSXEventsMethodsHostElementStylingFunctionalComponentsFrameworkIntegrationsOverviewBindingsAngularReactVueEmberJavaScriptStaticSiteGenerationOverviewPrerenderConfigBasicsDebuggingMetatagsServerSideRenderingDeploymentConfigOverviewDevServerPluginsExtrasCLIOutputTargetsOverviewdistdist-custom-elementsdist-custom-elements-bundlewwwstatsdocs-readmedocs-jsondocs-customCopyTasksGuidesAssetsBundlingDesignSystemsFormsHydrateAppPublishingServiceWorkersStencilStoreStyleGuideTypedComponentsWebWorkersTestingOverviewConfigUnitTestingEnd-to-endTestingMockingVisualScreenshotDiffScreenshotConnectorCoreCompilerAPICompilerAPICLIAPIDevServerAPICommunityStencilonTwitterStencilonSlackStencilonGitHubLegalTelemetryPrivacyPolicyReferenceSupportPolicyVersioningBrowserSupportFAQUnitTesting Stencilmakesiteasytounittestcomponentsandapputilityfunctionsusing Jest.Unittestsvalidatethecodeinisolation.Wellwrittentestsarefast,repeatable,andeasytoreasonabout. Torununittests,runstenciltest--spec.Filesendingin .spec.tswillbeexecuted. newSpecPage() InordertounittestacomponentasrenderedHTML,testscanuse newSpecPage()importedfrom @stencil/core/testing.Thistestingutilitymethodissimilarto newE2EPage(),however, newSpecPage()ismuchfastersinceitdoesnotrequireafull Puppeteerinstancetoberunning.Pleaseseethe newE2EPage()docsonmoreinformationaboutcompleteEnd-to-endtestingwithPuppeteer. BelowisasimpleexamplewherenewSpecPage()isgivenonecomponentclasswhichwasimported,andtheinitialHTMLtouseforthetest.Inthisexample,whenthecomponent MyCmprendersitsetsitstextcontentas"Success!".Thematcher toEqualHtml()isthenusedtoensurethecomponentrendersasexpected. import{newSpecPage}from'@stencil/core/testing'; import{MyCmp}from'../my-cmp'; it('shouldrendermycomponent',async()=>{ constpage=awaitnewSpecPage({ components:[MyCmp], html:``, }); expect(page.root).toEqualHtml(` Success! `); }); Theexamplebelowusesthetemplateoptiontotestthecomponent //mycmp.spec.tsx //Sincethe'template'argumentto`newSpecPage`isusingjsxsyntax,thisshouldbeina.tsxfile. import{h}from'@stencil/core'; import{newSpecPage}from'@stencil/core/testing'; import{MyCmp}from'../my-cmp'; it('shouldrendermycomponent',async()=>{ constgreeting='HelloWorld'; constpage=awaitnewSpecPage({ components:[MyCmp], template:()=>(), }); expect(page.root).toEqualHtml(` HelloWorld `); }); SpecPageOptions ThenewSpecPage(options)methodtakesanoptionsargumenttohelpwritetests: OptionDescription components Anarrayofcomponentstotest.Componentclassescanbeimportedintothespecfile,thentheirreferenceshouldbeaddedtothe componentarrayinordertobeusedthroughoutthetest. Required html TheinitialHTMLusedtogeneratethetest.Thiscanbeusefultoconstructacollectionofcomponentsworkingtogether,andassignHTMLattributes.Thisvaluesetsthemocked document.body.innerHTML. template TheinitialJSXusedtogeneratethetest.Usetemplatewhenyouwanttoinitializeacomponentusingtheirproperties,insteadoftheirHTMLattributes.Itwillrenderthespecifiedtemplate(JSX)into document.body. autoApplyChanges Bydefault,anychangestocomponentpropertiesandattributesmustcall page.waitForChanges()inordertotesttheupdates.Asanoption, autoApplyChangescontinuouslyflushesthequeueinthebackground.Defaultsto false cookie Setsthemockeddocument.cookie. direction Setsthemockeddirattributeon . language Setsthemockedlangattributeon . referrer Setsthemockeddocument.referrer. supportsShadowDom ManuallysetifthemockeddocumentsupportsShadowDOMornot.Defaultsto true userAgent Setsthemockednavigator.userAgent. url Setsthemockedbrowser'slocation.href. SpecPageResults Thereturned"page"objectfromnewSpecPage()containstheinitialresultsfromthefirstrender.It'salsoimportanttonotethatthereturnedpageresultisa Promise,soforconvenienceit'srecommendedtouseasync/await. Themostusefulpropertyonthepageresultswouldberoot,whichisforconveniencetofindthefirstrootcomponentinthedocument.Forexample,ifacomponentisnestedinmany

elements,therootpropertygoesdirectlytothecomponentbeingtestedinordertoskipthequeryselectorboilerplatecode. ResultDescription bodyMockedtestingdocument.body. doc Mockedtestingdocument. root Thefirstcomponentfoundwithinthemockeddocument.body.Ifacomponentisn'tfound,thenit'llreturn document.body.firstElementChild. rootInstance Similartoroot,exceptreturnsthecomponentinstance.Ifarootcomponentwasnotfoundit'llreturn null. setContent(html) Conveniencefunctiontosetdocument.body.innerHTMLand waitForChanges().Functionargumentshouldbeanhtmlstring. waitForChanges() Afterchangeshavebeenmadetoacomponent,suchasaupdatetoapropertyorattribute,thetestpagedoesnotautomaticallyapplythechanges.Inordertowaitfor,andapplytheupdate,call awaitpage.waitForChanges(). win Mockedtestingwindow. TestingComponentClassLogic Forsimplelogiconlytesting,unittestscaninstantiateacomponentbyimportingtheclassandconstructingitmanually.SinceStencilcomponentsareplainJavaScriptobjects,youcancreateanewcomponentandexecuteitsmethodsdirectly. import{MyToggle}from'../my-toggle.tsx'; it('shouldtogglethecheckedproperty',()=>{ consttoggle=newMyToggle(); expect(toggle.checked).toBe(false); toggle.someMethod(); expect(toggle.checked).toBe(true); });BackNextContributorsContentsnewSpecPage()SpecPageOptionsSpecPageResultsTestingComponentClassLogicSubmitanedit×Thanksforyourinterest!Wejustneedsomebasicinformationsowecansendtheguideyourway. >



請為這篇文章評分?