Clicking radio button in vue-test-utils with Vue

February 17, 2023

Let’s say you have a Vue template with vuetify that looks somewhat like this:

<v-radio-group data-testid="radio-group">
    <v-radio value="first" label="First value" />
    <v-radio value="second" label="Second value" />
    <v-radio value="third" label="Third value" />
    <v-radio value="fourth" label="Fourth value" />
</v-radio-group>

I’ve omitted things like v-model in this example, but you could add that to you radio group as well.

If you’d like to be able to integration test this component in vue-test, for example by checking that the click changes the v-model value, then we have two different options

1. Add data-testid’s to each v-radio

One thing possible solution is by simple adding another data-testid to each and every one of the v-radio‘s. That would look like this:

<v-radio-group data-testid="radio-group">
    <v-radio data-testid="radio-first" value="first" label="First value" />
    <v-radio data-testid="radio-first" value="second" label="Second value" />
    <v-radio data-testid="radio-first" value="third" label="Third value" />
    <v-radio data-testid="radio-first" value="fourth" label="Fourth value" />
</v-radio-group>

And then you could simply test clicking on it like this:

it('should click radio button', async () => {
    const wrapper = createComponent()
    const radio = wrapper.find('[data-testid="radio-first"]')
    await radio.trigger('click')
    expect(functionWasCalled)
})

However, in case you want to click all the radio buttons, this may be a little bit of a hassle and could possibly clutter the template, so there’s option 2 which I prefer.

2. Get items through v-radio-group

In this example, we first just find the v-radio-group element, and then inside of that find all the inputs, since Vuetify nests them quite deeply.

it('should click radio buttons', async () => {
    const wrapper = createComponent()
    const radios = wrapper.find('[data-testid="radio-group"]').findAll('input')
    await radios.at(0).trigger('click')
    expect(functionWasCalled)
    await radios.at(1).trigger('click')
    expect(functionWasCalled)
})

This way it’s possible simply use at(index) to click the correct radio button, removing unnecessary finds in case we need to test all clicks.


Profile picture

Written by An anonymous coder who lives and works building useful things. Mostly focusing on Django, Vue and overall Python examples.