8

I have a component Foo with Vuex binding mockedVuexBinding (which is essentially a computed prop).

I want to keep tests simple and don't want to mock the whole store. All vuex bindings I just replaced with computed stubs in test, like this:

const wrapper = shallowMount(Foo, {
  computed: {
    mockedVuexBinding: () => 'foo'
  }
}

But then It turns out that I need to test some behavior from Foo, which relays on change of computed property. So I want to update my computed with a value and test how component reacts on it (e.g. emits new value).

There is no such method as setComputed by analogy with wrapper.setProps or wrapper.setData, so how can I do it? How to replace a mocked computed value with different value?

Maksim Nesterenko
  • 5,661
  • 11
  • 57
  • 91
  • Use any `method` to trigger your change in `computed` property. You can trigger that method using `wrapper.vm.{yourmethod()}` – Satyam Pathak Jun 18 '19 at 15:15
  • @SatyamPathak not quite sure that I understood you correctly. Do you suggest to create a special method in component, which I will use only for testing, which will mutate computed? I don't think it's a solution... Also in component those "computed" are common mapped things from vuex, which can not be mutated directly from component (well, technicaly they can be mutated for sure, but it looks like some crutch in code for testing anyway) – Maksim Nesterenko Jul 03 '19 at 19:32
  • There was a setComputed method. This has been removed. In this issue you will find a copy that you can still use. https://github.com/vuejs/vue-test-utils/issues/331 – lars.a May 25 '20 at 13:03

1 Answers1

7

As usual we can mock everything, in order to mock behavior when computed value changes during test we can do the following:

const wrapper = mount(Component, {
  data() {
    return {
      computedSwitcher: false
    };
  },
  computed: {
    someComputed: {
      get() {
        return this.computedSwitcher;
      },
      set(val) {
        this.computedSwitcher = val;
      }
    }
  }
});

And then when we need to change computed during test we do:

wrapper.vm.someComputed = true;

In other words we link computed to a mocked computedSwitcher that doesn't exist in a real component just for the purpose of testing to mock computed behavior.

One thing to remember, if computed value triggers re-rendering and we want to check something connected to this, after changing computed, also call

await wrapper.vm.$nextTick();
Alonad
  • 1,986
  • 19
  • 17