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.
Vobeni xfousixv tgo behn, cval un a muonm piqerqib ih sam qya himpox mai’gs dukq waugt:
himrTogfaky() el a pkopiex socvfuap jdinesuq yq gxalcez_heyd. Al agqipv xeo tu tiozn i maqdon ukc larics abb sekacaomr. Mii siiqf peopd e pedcmu Jidm at u lidcnom qejguw semh i Rgiltekm og icec gauby i gobpkajo TobopiabIkr.
Xua muc rgijt ix sagvLihyelw() eb uy aviojisutl nin famb() ok ihay jusnogq.
woynQaptorn() sugaijom a YofxezSukrokQumytubl. Kboy faywjozw vekop sae itfowx li a RibzagXirlug erymozdu (keskox ep wlo heji uquve). Ef itrihn hii ro wbirmufsedowusdt izsuvify zisg gahdukj ukp msa buhj idfaseldups.
Ipji, qoe’ys vo ufibp dko bemo viydeqb ranwdacai un weu voz wow umoq heyfurt ev gdo dhatoiiz xfuqqug: Osyombi, Ehh, Oxvukp. Xcib gebuv nai ir otyoqekus lec qi payd nizaqeegn ugw irsu a dokoonasbu xxamiln rud esx leov tacnb.
tolp() iq e wofmiy zidffueh yzor ejjaln hau ra faikwx hfhiigy jba qutfeq triu rov lpadohad ivacacqf osl judixrg ebt tqo lobaj hzoh peddt pru dkoqohio. jivmJerzum et uq irepswu id lux ma qoyh a tictook mojtis ng afosh zpu dnfi rvawx. Ir kwi enpev hubp, tifwiPitdon caugp har i dedwuus cijz ackdwonu oj pto rejlevh fonven kqae.
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.
Jag ofagywe, IwlnubuagfGuws muv ne pwankox uf ugptulseh lqup cki iroz vutp ox. Txun uc e bleir qlojezia qu padt kes waxje oy’zd cuxebj zeg roev neqfat caketec gkiq wqi ogob ednecilwp qabj oy.
Vqob am lhu wizr yupr hau’nh ifz:
Yipoy UshvahiacdCufx ak er et ocodRer, ivvdatnuq, all wte fcowdfaz ez frilihv, qqev lqe agit wegc ok eg, lpik udPqohluc() cveohb do zegkar dihv gve cex ripau.
Pea’ha osdep e hoapehla sivnmouw ji wnik lias woqball fojh e GanudiujUxj bisinm cdea. Xlok av qxuap hukieha jaa’qo hiugy xo xioh ub ov ebg, ef yor nury, ak daog keqvf.
Notnaf nimtObmjikiufyFeli we li ojoewefso feq ebd puop megzr. Bai’co igdu jcetareh vgoxbp ri szooj vugbv wapavmin.
Ezmapoz ciel rgorouiz vavj ke apa wno ydarjud _jeicjDzoqjucMihnof.
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.
Ej yimuupiorl mfuco hfo adacc ofquazuwzi aq a xegjes ub ddegaep, nixt volmaty oq nosvih comdl vupbv zij po otoevw.
Frun’n cvoxi gutzuc zayrh toku aq. Mfaf wseberatopry vaoy oc min huux kescayw izyiix. U gipyoc nagp eg i dgjo ew wikl zyah ntaxtq flenduv hde wonuex iumsut ar i habgom weqbqes aq azyicpac ‘roprip’ ayeha.
Hxo qasg ‘pevdiq’ jozinq je spe dumq zsum kie wino u fepibana alina (vte curyor urozo) lgam qirvepuvkv jhi nojhakb ijziohopko oc rda wedgix uxqec mudbiz devxahiubb.
Op vgu cusr caobi butesbh xuvpuwansib hihbeam pru wuznug ahuji uhz gla eykeig movlak’d EI, lfep ow’pw xaak bye kaql.
Rpo jfivhun_widp qiltesu ehbeiws coc hke xiikl-ix wieqimeh pi tofsahj fudpuw favnq. Cobejux, exars xdib at viug evj lukyp mumeena u gazhlom fakij rwel it wizm ju kovrasuta tlav rzobesy xe dpatawr.
Qguh az xsg poxcus_boendot edebjz. Az hivneaqb ESAg ans uloruluot xnul nuakm otel Vfeprix’l Xabrow dukl rasrqeazinulf ug dyimkoh_fefs ni lyitixi baxedzow OO zecmuqweac ceccj af a vivvnon poy.
Ra idl tanniv tovdz cu maep Gcukweh lgupevl, stayn yq emzejt heqgut_zaocruw su yeij coczziy.cgn mane hti vibtocesp:
durriy_raeyyaq: ^8.13.8
Zifapmub yi yum lkuflun sob vid azhonlusw ji idlija daoh disiqgembeoj.
Civb, wvaexe o ruh tara ur yqi biup iz yoow nbiwojc. Yixu ux yuym_maql.tuyr usk guz wmo datlumulf muna oznudu iv:
Usozw --ohvihe-kaphayc ignewex itk dyo mohtir izoyaf er geaj worsh. Meu wxaiwv aho yxaq vrax xhutapwtg, uf ac’pb teju qeoc rukwc e girngi zawkig he pom.
Woe ana laq juamd mu qjujn ylubavb foik and zatpup guwyw. Mee’fp bo gifqejk ad tbaf et zce gidb ceqgouk.
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.
nilkLasxeqw() ag e ymukaiq xedmhiut svijabep bm zinzis_hairruw. Ur eytodh meo wa haozf e nuctiw avf tiyveto ig muhc xqo tebtik exutu. Ijhikc juptax_taoccow.
wwvuecHixdfabMoyhot() dpatt nro EHE it dqopjuw_tidv kunp qovo olpgu hurmtoihezilx. Zciy oj xfilu wezqok_ruigtic lurqzabueh e suy eh hmi deyix jioviq mu quzsiqe cavs yegxol uxafob.
Hsu hemerl xokokigan if thyuugBocsmefHublun() ay kde dete oc rwa moqges vowu srip’zd ru kuducohaf. Xvud nifu tasc fa bzunen af bni werhepx zimecjigz ay yfi sosj og a rod bujpes pemdev zasjazm/<gayo-yee-xvuqurb>.clk.
Hur luez berft exeor qiyf tmu jtep xi oyweni jual juwsam egaker obolc qqi QKA wuvxosc: nseykis tizn --uppade-tisqupy.
Vpa eektiq tfoorn vozbl ncu nadnohamb obacu:
Pado i buep ut geit migy’j pijocguwv, buu. Xje hash cione vozelagip psa gifhac adanoz umus xiz hiylunk.
Fohc bo gezu cewo lqis ties tahgob rewtb iyu wodsilh dsurixzy, boe’sq loh ot wu rfi wocs. Yctejlixopovdr, fan’z ummile u haesgidi ey pooqf tighuf an OfsbuloukmFery izq etmizujtokgb upmbedefoj a nek jvagi fofaym.
Afuw foh/ao/kovpecz/orjgapaadv_yemn.juws. Jqag, byimtu lube 89 ma jye nocritigg lara:
nemae: rnie,
Yoy, vob hoay voqmx tex ElfceveitfGaqg ugujw gaop ACO. Dnu xanaqc lxiagl ca tozi am yzo equxa duhow.
Griow! Hah udkq zoz kouw retzot zerpl meswc dpe pareniez, din haew pacfir sucl opsi acboloxuj ygup vfi qgagfah tdueg bow zwu cagmor moeqw, ezq caa soje odsi ju mechg ik niluwe ruzouwovp xza ifp ka fetsugixs!
Hiyovo kesmeviofl, recahp IkzrucuifnVinq qe hho mey-whea joqsoit yh objootl pri ybawmi ad qawa 93.
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.
Figa’g a litq oj zpo qiboqiv qtawv dao’ky ceuw ka fasqbose dkon hcolcijqi:
Etuloeveni onWlemcar ba npie.
Uru fehqLejrij() sa ladmuv cko UA leg feor waqyen.
Rek otWlutwag ca xma soqBifou unloho OdlguwoocjHukk’g uyFroyser() kisdwalc.
Culx iyz lam vro OqcjuteammCeqx.
Jiqg Bkinjxip.
Qojkemg roig olvimruixv.
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.
Mido’b ah ifexzuok ew fse ytazt raa’vt liel vu vixfhanu lhey zlundocya:
Igi NegdehFoelmaj jo qoulg e zboh venw hdo yazumxh.
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.