Following Vue Test Utils
's docs I created a test store (replicating my real store) in my test:
In it there's this action:
actions: {
updatePowerSelectedAction(
{ commit }: ActionContext<State, RootState>,
val: number
) {
commit('UPDATE_POWER_SELECTED', val);
},
},
... which the tested component calls when a button is clicked:
Template:
<button v-for="(power, i) in powers" :key="i" @click="comparePower(power)" />
JS:
function comparePower(val: string) {
updatePowerSelectedAction(val);
...
}
I can see that the component is properly loaded, however it fails to call the action when a button is clicked via await wrapper.findAll('.button')[0].trigger('click');
.
There's no error message, the action just isn't called. Why not?
In your BattlePowers
add a class named powerbutton
to make that buttons unique :
<button
v-for="(power, i) in powers" :key="i"
@click="comparePower(power)"
class="button powerbutton"
>
{{ power }}
</button>
then inside the test file battle-powers.spec.ts
import the global store instead of creating new one inside the test file since this global store will be affected when you mock the button click :
import { shallowMount } from '@vue/test-utils';
import BattlePowers from '@/views/battle/battle-powers.vue';
import store from '@/store'
describe('BattlePowers', () => {
it('updates store variable powerSelected with power clicked by user', async () => {
const wrapper = shallowMount(BattlePowers, {});
await wrapper.findAll('.powerbutton')[1].trigger('click');
expect(store.getters['powerSelected']).toBe("strength");
});
});