Mocking a getter in Vuex + Jest | Toucan Toco

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

You don't want to use the “real” getter, because that would not be a unit test ... Pizza.vue'; const localVue = createLocalVue(); localVue.use(Vuex); const ... HOME BLOG MockingagetterinVuex+Jest MockingagetterinVuex+Jest|ToucanToco NinoFiliu TableofContents Let’ssayyouwanttounittestacomponentwhichbehaviordependsonaVuexgetter. Let’susetheimaginaryexampleofaPizzacomponentwithaisVegancomputedpropertythatdependsontherecipeVuexgetter:amargheritapizzaisnotvegan,butazucchinipizzais. Youdon’twanttousethe“real”getter,becausethatwouldnotbeaunittestanymore,soyoumockit,andallgoeswellatfirst: import{createLocalVue,shallowMount}from'@vue/test-utils'; importVuexfrom'vuex'; importPizzafrom'./Pizza.vue'; constlocalVue=createLocalVue(); localVue.use(Vuex); constrecipeMock=jest.fn(); recipeMock.mockReturnValue('margherita'); conststore=newVuex.Store({ getters:{ recipe:recipeMock, }, }); constwrapper=shallowMount(Pizza,{ localVue, store, }); expect(wrapper.vm.isVegan).toBeFalsy();//pass Youmoveontotestingwhathappenswhenthegetterupdates,andwithhorror,youobservethatthetestfails: recipeMock.mockReturnValue('zucchini'); expect(wrapper.vm.isVegan).toBeTruthy();//fail Tryingtounderstandwhatishappening,youaddlogsinbetweenyourlines: console.log( wrapper.vm.$store.getters.recipe,//margherita wrapper.vm.isVegan,//false ) recipeMock.mockReturnValue('zucchini'); console.log( wrapper.vm.$store.getters.recipe,//margherita wrapper.vm.isVegan,//false ) expect(wrapper.vm.isVegan).toBeTruthy();//fail Argh,thegetterisnotupdating,eventhoughweclearlyaskthemocktoreturnsomethingelse! Why? BecauseVueisreactive:itdoesn’tupdateanythingunlessittrackedaneventthatisexplicitlychangingthestateofsomething.Sometimes,it’shiddenforconvenience,likewhenweupdatedataproperties,butthereisnosuchthinghappeninghereandVuecan’tmakethelinkbetweenthemockupdatingitsreturnvalueandthegettervalueupdating. Theonlywaytoupdatethegetteristocommitamutationthatwillimpactastatepropertythatisusedincomputingthegetter.Thatwouldlooksomethinglikethis: constlocalVue=createLocalVue(); localVue.use(Vuex); conststore=newVuex.Store({ state:{ testRecipe:'margherita', }, mutations:{ setTestRecipe(state,value){ state.testRecipe=value; }, }, getters:{ recipe(state){ returnstate.testRecipe; }, }, }); Yes,it’snotperfectbecausewe’reintroductingstatepropertiesandmutationsthatdon’tactuallyexist,butgiventherightprefixorcommenttosignalthat,it’sanacceptabletradeoff. Anditworks! constwrapper=shallowMount(Pizza,{ localVue, store, }); expect(wrapper.vm.isVegan).toBeFalsy();//pass store.commit('setTestRecipe','zucchini'); expect(wrapper.vm.isVegan).toBeTruthy();//pass TableofContents readalso 6ReasonstojoinourTechTeam readmore TalendspeaksToucanToco readmore Learnhowtoautomateyourproduct’sreleasenoteslikeabadass readmore



請為這篇文章評分?