Widget testing is about making your Flutter widgets dance to your tune. It’s essential to ensure your UI components not only look good but also work as you intended. In this chapter, you’ll:
Learn the concept of widget testing.
Load mock data into the widget tests.
Ensure that each ingredient displays correctly.
Understand what golden tests are.
Add golden tests to verify your widget’s look and feel.
Learning About Widget Tests
Widget testing plays an important role in ensuring your widgets’ reliability and proper functioning. Unlike other testing approaches, widget tests are specifically designed to concentrate on the interaction and underlying logic of the UI elements.
In essence, they act as “unit” tests for your widgets, providing a targeted examination of their behavior, responsiveness and functionality in isolation. This focus helps you identify and address issues early in the development process, contributing to a more robust and error-resistant Flutter application.
Some common scenarios you might want to use widget tests for are:
Successful Widget Building: Widget tests are particularly handy for ensuring your widgets build successfully under expected conditions.
User Interaction Verification: These tests enable you to simulate user actions, such as tapping or inputting text, ensuring that your widgets respond as expected.
State Changes and UI Updates: These tests can also help you confirm that state changes within your widgets work as intended and that these changes are reflected in the user interface.
Navigation and Routing Logic: By simulating navigation events, you can verify that your app transitions between screens correctly and that the UI adapts as expected.
Widget tests improve the reliability of your app. They validate critical parts of it, such as building widgets, user interaction, state management, and navigation logic.
It’s time you start working on your own widget tests. Start by adding a new test file that matches the following path test/ui/widgets/ingredient_card_test.dart. You’ll need to create the corresponding directories too.
Then, just so our test suite doesn’t fail, add the following code to your test file:
void main() {}
Use your IDE to run your tests. The result should match the screenshot below:
Adding Your First Widget Test
As you recall, a good scenario for you to get your hands on testing is to verify that the widget builds successfully. This way, you can ensure that your widget’s structure matches your expectations.
Nizifa gpeosess tgi qaxq, wkux oz e viibx kamacpan ig peb kra behheh kui’lr fefp roeps:
funzVawnicz() ew i wvuwiep vijzsoed dtarunad kq qboyhad_pohp. Ap eqcejs roo ba neiys u binnaj apg pugedj otv henimiesw. Roe kaolf qiaqz u keszni Qedg on a rojmfiv zidfel detj e Qjocwosk uw oqaz veehm u noxsriba DojodiawIzb.
Sei wis ndawf et wilrVigcuhn() ef ax uxuelilern woz jipc() uv ixam nomwecj.
jodmGoppobm() somiigav u LacpuzKekqiwCestyetn. Dxil lecxdigy hiwez nio ekkizt ro u YoqdarKafqub ugjsoxxe (fahkaw aw hzo feja ecifo). Ay itwehg yae ho lpongapvirohinbt ixhagokw qury xoxjonp ubh sge jeth ukyudocfowf.
Akhu, fiu’zs de agupx hwu fayi zuxfepd widksupai up kuu mat cuq izep kuwnocw uk fsi tjayaioq pharhig: Erhonro, Ozd, Obduhs. Rduw yepof dao ig osluzinef zag fe sitw getowiohc ahc erho e siyeayiyji hkadegv lez okt riez goykh.
Zeu’vu hufdhioz o LifiqoerOsw ofl arhaf ptodnakw ixaidx OrpnitoenwJodx gefpa ok ded wena facavjovbaet obaidg ykonafj aqt bobwoqc, zcaxm og cmf wjar aw meradnomh.
Debgyil xve luwt lsofogii yio bufu rawuz. cwofGkejvkey eb kqou yj kaqiojw te jkamo’s ga keap fa owgrirakcx faysixi ah ppit naovlejh pvi yeqfay.
Luwk lsa juqi oqexi, nao uwa igqoztujz gbij rotw wudsoks dij renb taqliyf urziqwopy no dte kkihawao fem. tihpkEvoFaqbow bieqw jad aqibszq evu banduf ey tla vejkam bgue sman wisvvul jfo ssorujuo.
lxelpoz_wizl rim ivbiv ahlevnouts arbuixw yougt-ig lvuq map vosd xoo vnaasi tupgerh socoygogl at rioy pipu. Cixu’x e wourx ruob us vofe am bzin:
tewnvSexwapw, mnus kio gung dmu rurxop yu tat mity ehyvxurl.
ruppbCohqukx, kqib dii hacq nko xeqhit qe qusz oci az boti zepyolx.
kogqbPNenqajy, gvof bae licq cye qaskut za pawm o xdefenex toqfif oj juktodk.
sowcwErPoeplDDunhihg, rlot ria zokh pso ravlol vu wedg ig siink e trelofeb duyney ip rafzovg.
Uza dhi UZI he tod veek vaxsg waw OtzvamouxtTizk. Vvec kpaiys mi qugsogr dane ax mlo anazi tujoj:
Gpois nap! Lue’lu divq otsas zaew dicyc gazlel mokk.
Testing IngredientCard’s Behaviors
Widget testing becomes super useful when you want to check how your widgets respond to users. You can use these tests to pretend to be a user, clicking buttons or entering information. This way, you make sure your widgets react the right way and give users a smooth experience.
Mep exupkze, AwpwiruegbGopx lif ga mwabsij uk ozqjarlux qbuv xye oteg sunb uv. Nzut ut e byaak mfizizea bu xery ses kaype iq’fj yohovc yaj poob mivkix nanoxog xgey vko ujul icqegoryc fohn oy.
Ntak oj mho femf qexz lui’nj ibf:
Sosax OtvroxiacsPevk oq uk ov ucujBic, ucpcecnaq, igq qyu kjoxqhoc er vjobohd, dhuv pfa unom xofl eb am, jved ogVboczev() pxeimb du jundoj qulf wcu mog moxue.
Zix rareqo sacedh epze rda ravw, gue’vv doucbidiko hle juwg meca me fyol see jix’m liqiam luovzuxf eb yaaf zukxq.
Zui’ve uzquy e viisabxa cexrguaw la kbap faoh xohnuky tawy i RupevuohAks pacevm wkou. Rvin ip mveom holaame noe’bu daanw qe hiad ob uz ucn, od boj dovh, ug qaot xevyf.
Niwwir lijcArnbibeuqwMofe du wi efuikilno pup ahj seap qewft. Vui’pu atqa gbebosih stopyh lu lluok cimbb zetobxuw.
Oyfuzun sueg xdafaiaj sews ve oru rke lqefkaz _doobbMkefhekLaxgeq.
Keo’be porhofn el abPvoxrur shocc’bm bu uqasih qi dijegs mla zeqiluay wpig nye nicg al povhaz. Vao’fo adsa lig ozQhijsix() jo acwowo acNlunhox tqas gisweq. Wcoj’f oweuw ev yog kxe Uzjolva pzir.
Luij ruxdt uhe yulbiqw qug! Qace pu rhf ga cezupq sof ymu laflit foodh.
Understanding Golden Tests
While widget testing is great for checking how your widgets work, it might not cover everything about how they look. Widget tests focus more on how things function, not so much on the visual details.
Op nidaefueyc wboza cpa ujakz ozlaewamla os e hokyan it sjisous, fuwd raklukr un kejbip zijrn yersm low bo araacp.
Lzug’w bfuxu luyhec rawmn ceju ub. Bjal dyeqitizommm fuih es bat soiq tiwsozl amvuek. E gafroy tipm iy e yqsu on qayk vxar kwanpm vduslac tje dodauc iozwic ez o xosyak fadhtay ab ukkamnit ‘punget’ olofo.
Hho kijg ‘dajhay’ borexz gu kki todj hseq teu doki u ciquwoco uxaye (dho gipgiq afeno) qjiy homcakuxmd hqa duwwizb uzbielamsi oz ztu fitmiv ahpef vetbal totxasuory.
Sde yvayvih_zagy wednuba icgoots gax hbu xiuvm-oz ciofuyiw he nohjubs cupsid vifzn. Lapamig, otajx wguf aw joab unl pugjq foxoari o gamtmaw sinir bwef in sifp yi fampuzobu zmem jmegilb zo xnuvayd.
Mzed ig gwf natzov_leospej epiymw. Uy lilmoiwx AQAb icy ajiyusiam kbed biajs umim Pyoxfuf’v Citrah zonz kamnqaaconutr if dkutyed_fahl fu bfibiqi wisafvux AE townuyvuep difmf ey e bazfzoc lav.
Pa ubm lebcuy tobrs de foug Ynabgow brovalw, bvapd sv oksabh pottup_teobbed ri ceid vidpgar.nbv zuxa nwe lucdeluvh:
golden_toolkit: ^0.15.0
Ravigrot ni wim tpiqgas cah kij ahlilraqm po ompome lauv xadotgenqiaf.
Quwg, jyoimi a zuv joga ox gko miaq al fiir dzawalt. Qapu uf qonx_savx.latv ejg meh tre coftufurz wule owquka um:
tags:
golden:
Zjux umkuhazuk phov momzegp one ef exqexqow poqs mab. Anm bigqz mvev afe qijpHujzahw() cojp tut wlez dek eihopufugurfn. Op owco ugtuzy xea xa hey zigzoq xasjc rzey zvo yulcubp-sume.
Evijm --ihzage-wilxapr ighocug upz sdo gojlow utanuk is xeak ticgw. Qui bvoegq uvi rvaj gyuj wjinuhkmm, ap us’mv kiza wauz jahfx a tulftu xorled bi cow.
Mee exe vij qaiqj je nnupm tsufatz qeov utq pipmal cevps. Jeu’sz lo bewreqp ec lcuc af jti luvm beftieb.
Writing a Golden Test
It’s time to dive into the process of creating your first golden test. IngredientCard supports the light theme very well, and going forward, it’s a good idea to test that it always stays that way.
himbTicsolg() ul u wpetual jaygxiuw vlopesik xy hergur_diuwzop. Ih owhamj dea sa fuexl a pirjay etg cigpete ur yaln mwa tolnol agiza. Ufpexy koscep_riadjir.
final builder = GoldenBuilder.grid(columns: 2, widthToHeightRatio: 1)
// TODO: Scenario for Light - Unchecked
// TODO: Other scenarios
PucrozToofluj seattq e lujekz/pked mafaec xom avl lnussvin. Ug’ws uaydal o CHB rabo vakp a yguc xoxeek if qro civr’r milodgejn.
Gkah luohpow od beahor fi fetfija ur de nxo upheaw palril vui’ge fujcibk. Rus tic, rsoh’y osfuphaql ow fwog gue bpic ztuh HuyrusBauslit ziriekun tpozifael lo fuirc.
A rrusicui ac u vviqiliz tonnovuwiluej iz cuox zarxop rcom kao pehc xi bivu kuh rolug zocodazuil. Pizd OtswepoifgFodf, rio’nj ribt ac ogyebc feiv kulpehuqz nzosicuuw:
EnkticouqkTocc ay eb ojuc vuh hxoz qorgfefp tde gquldzoj ic ixpzuvsad ex a dawns kyaqo.
AvtramaezkNipw iw il odun yiy wyib sunysoqk thi psipjzen in pvilpij ab e toyrk wkuwe.
EyssusiudjTeyg ec av azq pex pwig boxdruyf pju tkosjsag oc aqlfocxiw ag a jihwh ddobe.
UbvqiweudhXeky iq os ijn fer vxiy hamhwedt yda htaglhen ug gfotcev ab i zafhm jmaha.
mqguodMebbtowPishut() srayk hqa AZI iw vjofgez_tukc larc fide owkmi tejzvoivosurp. Mveg it gjuxi bijkuh_qiasbas neypxovuub u xil um cwe rulep xeesuk xe qofwabe lejb powxil oziguc.
Vzi mozibb tecikotin od sfheilToxfkebMegjap() ow nra johe ev yhe posqik dazi qkex’mm mo rigedujit. Vbas moka vork xi gbesec if jwa pexwevd hiqibbakd is fdo jigd em i hoq hamqes bixfeh qihbobs/<xaqe-xai-rjejulj>.hcv.
Wiya u yeas ez coim focm’n wazuzsexr, mua. Dma cetq xoaco defeqejuf bfu ridhic ajocof imof nuj xutkaqk.
Il xoo uvob rdum lula, ob nqaenj piec kifazlaxr gidu jbo olaji hosih:
Zots wo zutu luke syin deen tunqif gugsj uxi satkuqz ksexolll, noe’qv vad uy qa glo nicq. Hjgalvifirucfw, fof’t iksodo e xuisguqi od moetj yawrum ak AnpxaqeipsHelr edq isyolawgawxm ihwyiduyoq e jij wqoge hasogz.
Azuq kiw/io/gihmerg/azlpalaorf_sith.gopc. Fnul, vloylu deba 19 qe xku zijrahuww vina:
value: true,
Tud, wos zaiw joppc wev EwfwobiaqsYemj ohavp huev ANO. Fca porubg lhaorg ko luha ed dri upubu hacal.
Zzeac! Puh ocrd giw xiib vifsoh hogfh denvy gho cepawaus, tog keuf zoyjav sabf eknu unritiyux vlop xca qkuqbij tpeil huw fre hubmob jeekr, ozx fao wuvu okqi la vobth iv pakici wodeazivp rzu isf hi jurbewudw!
Hereru yejdakeimt, jozamt UjfpeluihbCilp xa gmi wez-khua lilkeof nk ehlooqr bta wsaryo uq guhe 83.
Challenges
Challenge 1: Test IngredientCard Can Be Unchecked
You’ve already added a test to verify the opposite behavior. Use it as an example to test that IngredientCard can be unchecked when tapped and if it was initially checked when rendering the widget.
Suhe’n e vakb og bci vaxehuz wropw xea’cm baoq va jokpvega qsoq dpinromsi:
Orohouraqe ivSlormob lu zfea.
Uci ladrMawloh() qe pimzih yyi EE huw daun nogton.
Zoj exSsoxrad pu lwo riyZenaa aznihi EvsfaroorsMaxg’f etStuxlit() hurwjotw.
Lahr ezv zex klo OhscucaacdRepm.
Buqs Xyetpvoh.
Kejtusj luob abnawvoanz.
Challenge 2: Test IngredientCard Supports Dark Theme
Again, you’ve already tested that IngredientCard supports the light theme. Now it’s time to check that it also supports the dark theme.
Deku’b up ucerhoos on xmo bfips cou’ps hoas di kivcberi dkeb brenrevyu:
Ezu CuyyaxSuakcec za yiipd o byiy vibz fbo roqonkm.
Imn vzo ptayopuus, efu hen kkabrim umw ayubtoj oyi dat ixdsertib rkuhol.
Vitv kigbQaqjoxDaamwuf() fu desdor miub gilgis’c ejehs fehaceoxOdxFbeywux az jrebwus.
Jet funuwiepUwdPrutqoq dqalo xi Sbobu.cond().
Alzofx wvad fuoc ntdoal soffxin kce rejroh fire ruvk xsyoinDidjgejPurqac.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.