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

Ale*_*rff 8 frontend vue.js vuex vuejs2 vue-test-utils

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

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

const wrapper = shallowMount(Foo, {
  computed: {
    mockedVuexBinding: () => 'foo'
  }
}
Run Code Online (Sandbox Code Playgroud)

但事实证明我需要测试 的一些行为Foo,它依赖于计算属性的更改。所以我想用一个值更新我的计算并测试组件如何对其做出反应(例如发出新值)。

没有setComputed类比wrapper.setProps或的方法wrapper.setData,那该怎么办呢?如何用不同的值替换模拟的计算值?

Alo*_*nad 7

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

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

然后,当我们需要在测试期间更改计算时,我们会执行以下操作:

wrapper.vm.someComputed = true;
Run Code Online (Sandbox Code Playgroud)

换句话说,我们将计算链接到真实组件中不存在的模拟计算切换器,只是为了测试模拟计算行为。

要记住的一件事是,如果计算值触发重新渲染,并且我们想要检查与此相关的内容,则在更改计算值后,还可以调用

await wrapper.vm.$nextTick();
Run Code Online (Sandbox Code Playgroud)