25

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?

Harold
  • 845
  • 1
  • 9
  • 17

2 Answers2

42

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.

ittus
  • 21,730
  • 5
  • 57
  • 57
  • 2
    Mocking computed in the manner you described is okay (using mounting options). `setComputed` is best avoided, though. – lmiller1990 Jul 07 '18 at 10:09
3

In Vue 3 (and it's current partner, Vue Test Utils v2 RC 18), you can still stub the result as @ittus mentioned:

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

However there is a catch, at least when using the excellent vue-class-component (v8 RC 1).

If you start stubbing one computed property, you have to stub them all. Otherwise, they will come back with undefined as their value.

So in this scenario:

export default class Home extends Vue {
    public get loaded(): boolean {
        return true
    }

    public get tipsy(): boolean {
        return true
    }
}

If you mount it as above, then this is the result:

wrapper.vm.loaded === true       // true
wrapper.vm.tipsy === undefined   // true

However, if you stub both of them when you mount:

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

Then this is the result:

wrapper.vm.loaded === true    // true
wrapper.vm.tipsy === false    // true
Paul F. Wood
  • 1,453
  • 16
  • 19