Search code examples
vue.jsvuejs2jestjsvuetify.jsvue-test-utils

How to unit test Vue component that append DOM-element to HTML body?


I have a Vue 2.0 component that uses the Menu component from Vuetify. I'm using the official vue-test-utils to mount my component during test.

The problem I'm facing is that the Menu component append the "menu" to the HTML-body (outside the scope of the component). Because of that I cant access it with wrapper.find('.menu') like i would with any other element in my component.

Is there a good way to access an element appended to the body using vue-test-utils?

Update

My component at this point looks pretty much exactly like this Vuetify codepen example

And I mount my component something like this:

import Vuex from 'vuex'
import Vuetify from 'vuetify'
import AuthenticatedUser from './AuthenticatedUser'
import { mount, createLocalVue } from 'vue-test-utils'

const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(Vuetify)

describe('AuthenticatedUser', () => {
  let getters
  let store

  beforeEach(() => {
    getters = {
      getUserDetails: () => { name: 'John Doe' }
    }

    store = new Vuex.Store({ getters })
  })

  it('should open menu when button is clicked', () => {
    const wrapper = mount(AuthenticatedUser, { store, localVue })

    // In here 'wrapper' won't have access to the dropdown menu,
    // since it has been added directly to the HTML body
  })
})

Solution

  • In your component definition, add a ref attribute to the content of the menu, in your case, the <v-card> component:

    <v-menu>
      <v-btn slot="activator"></v-btn>
      <v-card ref="menu"></v-card>
    </v-menu>
    

    Then you'll be able to access that <v-card> component via wrapper.vm.$refs.menu in your test cases.