Miguel Stevens
Miguel Stevens

Reputation: 9211

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)

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

In my test coverage however I notice the setter() is not covered. Using setData() I can modify my internal data, but is it possible, using vue-test-utils to test calling a 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
  }
}

Upvotes: 1

Views: 936

Answers (1)

Sneakster
Sneakster

Reputation: 155

Ideally your slider would have a hidden <input> that holds the value for accessibility purposes. 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.

Upvotes: 1

Related Questions