如何在测试中手动更新vue computed 属性

How to manually update vue computed property in test

我有一个带有 Vuex 绑定 mockedVuexBinding 的组件 Foo(它本质上是一个计算道具)。

我想保持测试简单,不想模拟整个商店。我刚刚在测试中用计算存根替换了所有 vuex 绑定,如下所示:

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

但后来我发现我需要测试 Foo 的一些行为,它依赖于计算 属性 的变化。所以我想用一个值更新我的计算并测试组件如何对其作出反应(例如发出新值)。

没有setComputed类推wrapper.setPropswrapper.setData的方法,请问如何实现呢?如何用不同的值替换模拟计算值?

像往常一样,我们可以模拟所有内容,为了在测试期间计算值发生变化时模拟行为,我们可以执行以下操作:

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

然后当我们需要在测试期间更改计算时,我们会这样做:

wrapper.vm.someComputed = true;

换句话说,我们 link 计算了一个模拟的 computedSwitcher,它不存在于真实的组件中,只是为了测试模拟计算的行为。

要记住一件事,如果计算值触发重新渲染,我们想检查与此相关的东西,在更改计算后,还要调用

await wrapper.vm.$nextTick();