简体   繁体   English

单元测试一个 Vue Computed Setter

[英]Unit Test a Vue Computed Setter

I'm using a computed getter and setter to calculate and update my localIngredient as when the value of a slider changes (left out for simplicity)我正在使用计算的 getter 和 setter 来计算和更新我的 localIngredient,因为 slider 的值发生变化(为简单起见省略)

The getter calculates the data to populate the slider with, and when the slider is moved, it should recalculate the original value, using the computed setter getter 计算数据以填充 slider,当 slider 移动时,它应该使用计算的 setter 重新计算原始值

In my test coverage however I notice the setter() is not covered.但是,在我的测试覆盖率中,我注意到 setter() 没有被覆盖。 Using setData() I can modify my internal data, but is it possible, using vue-test-utils to test calling a setter?使用 setData() 我可以修改我的内部数据,但是否可以使用 vue-test-utils 来测试调用 setter?

export default {
  props: {
    ingredient: {
      type: Object,
      required: true
    }
  },
  computed: {
    calories: {
      get() {
        return this.localIngredient.value * this.localIngredient.caloriesPerGram
      },
      set(amount) {
        this.localIngredient.value = amount / this.localIngredient.caloriesPerGram
      }
    }
  },
  data: () => ({
    localIngredient: {}
  }),
  created() {
    this.localIngredient = this.ingredient
  }
}

Ideally your slider would have a hidden <input> that holds the value for accessibility purposes.理想情况下,您的 slider 将有一个隐藏的<input>来保存用于可访问性目的的值。 With your component mounted via mount or shallowMount , you can programmatically set the value on that input, which after the next tick will trigger the setter method.通过mountshallowMount安装组件后,您可以以编程方式设置该输入的值,在下一个滴答之后将触发 setter 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM