Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I select an element by ref using vue test utils

If I have an image

<img class="pineapple" ref="pineapple" src="pineapple.jpg" />

Can I use the $ref

expect(wrapper.find($refs.pineapple).exists()).toBe(true)

instead of

expect(wrapper.find('.pineapple').exists()).toBe(true)

like image 370
AlexanderDavidson Avatar asked Apr 01 '19 13:04

AlexanderDavidson


People also ask

How do you use refs at Vue?

Vue can store references to DOM elements in a property called $ref . The first thing we have to do, is add a ref attribute to the element we want to reference in our Javascript. The value of the ref attribute will be the name of it within the $ref property.

What is ref attribute in Vuejs?

ref is a special attribute, similar to the key attribute discussed in the v-for chapter. It allows us to obtain a direct reference to a specific DOM element or child component instance after it's mounted.


1 Answers

You can pass an object to the wrapper.find with the ref property.

expect(wrapper.find({ref: 'pineapple'}).exists()).toBe(true)

From the Vue Test util docs:

Find Option Object

Ref

Using a find option object, Vue Test Utils allows for selecting elements by $ref on wrapper components.

const buttonWrapper = wrapper.find({ ref: 'myButton' })
buttonWrapper.trigger('click')

https://vue-test-utils.vuejs.org/api/selectors.html

like image 115
JaredMcAteer Avatar answered Sep 19 '22 14:09

JaredMcAteer