Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  })
})
like image 321
Christofer Eliasson Avatar asked Jan 10 '18 14:01

Christofer Eliasson


People also ask

How do I use Vue component in HTML?

The simplest way to get started with Vue is to grab the development version script for it and add it to the head tag of your HTML file. Then you can start Vue code inside the HTML file inside of script tags. And have the Vue code connect up with an existing element on your HTML page.

Can I use DOM in Vue?

If a ref attribute is added to an HTML element in your Vue template, you'll then be able to reference that element or even a child element in your Vue instance. You can also access the DOM element directly; it is a read-only attribute and returns an object.

How do I use Vue components in JavaScript?

To create a component, following is the syntax. Vue. component('nameofthecomponent',{ // options}); Once a component is created, the name of the component becomes the custom element and the same can be used in the Vue instance element created, i.e. inside the div with ids component_test and component_test1.


1 Answers

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.

like image 180
thanksd Avatar answered Oct 16 '22 15:10

thanksd