22

vue-test-utils 提供了一个 setComputed 方法,允许您设置计算属性的状态。

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

vue-test-utils 1.1.0.beta 版对 setComputed 方法发出弃用警告,该方法读取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

文档中的安装选项没有提到任何计算对象。我试了一下

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

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

但那些爆炸了。

为 vue-test-utils 设置计算属性的方法是什么?

4

2 回答 2

37

您可以在挂载组件时覆盖计算选项:

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

但是模拟计算是危险的。您可能会将组件置于生产过程中无法进入的状态。

于 2018-05-21T01:59:04.450 回答
0

在 Vue 3(它是当前的合作伙伴,Vue Test Utils v2 RC 18)中,您仍然可以像@ittus 提到的那样存根结果:

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

但是有一个问题,至少在使用优秀的 vue-class-component (v8 RC 1) 时是这样。

如果您开始对一个计算属性进行存根,则必须对它们全部存根。否则,它们将返回 undefined 作为它们的值。

所以在这种情况下:

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

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

如果您按上述方式安装它,那么结果如下:

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

但是,如果在挂载时将它们都存根:

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

然后这是结果:

wrapper.vm.loaded === true    // true
wrapper.vm.tipsy === false    // true
于 2022-02-04T10:47:49.810 回答