Setting up Vue computed properties for unit tests with vue-test-utils

Harold picture Harold · May 20, 2018 · Viewed 13.5k times · Source

vue-test-utils provides a setComputed method that allows you to set the state of a computed property.

import { mount } from '@vue/test-utils'
const wrapper = mount(Home)
wrapper.setComputed({loaded: true})

vue-test-utils version 1.1.0.beta is throwing a deprecation warning for the setComputed method that reads setComputed() has been deprecated and will be removed in version 1.0.0. You can overwrite computed properties by passing a computed object in the mounting options

The mounting options in the docs don't mention any computed object. I had a go at

const wrapper = mount(Home, { computed: {loaded: true} })

and

const wrapper = mount(Home, {context: { computed: {loaded: true} }  })

but those blew up.

What's the way to set up a computed property for vue-test-utils?

Answer

ittus picture ittus · May 21, 2018

You can overwrite the computed option when you mount the component:

const wrapper = mount(Home, {
  computed: {
    loaded() {
      return true
    }
  }
})

But mocking computed is dangerous. You might put your component into a state that it can't be in during production.