如何测试从 VueX 观察计算属性的 Vue 观察者? [英] How to test Vue watcher that watches a computed property from VueX?

查看:24
本文介绍了如何测试从 VueX 观察计算属性的 Vue 观察者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下组件:

import { mapState } from 'vuex';
import externalDependency from '...';

export default {
  name: 'Foo',
  computed: {
    ...mapState(['bar'])
  },
  watch: {
    bar () {
     externalDependency.doThing(this.bar);
    }
  }
}

测试时,我想确保 externalDependency.doThing() 使用 bar(来自 vuex 状态)调用,如下所示:

When testing, I want to ensure that externalDependency.doThing() is called with bar (which comes from the vuex state) like so:

it('should call externalDependency.doThing with bar', () => {
  const wrapper = mount(Foo);
  const spy = jest.spyOn(externalDependency, 'doThing');

  wrapper.setComputed({bar: 'baz'});

  expect(spy).toHaveBeenCalledWith('baz');
});

Vue test-utils 有一个 setComputed 方法,它允许我当前对其进行测试,但是我不断收到警告说 setComputed 将很快被删除,我不知道还有什么方法可以测试:

Vue test-utils has a setComputed method which allows me to currently test it, but I keep getting warnings that setComputed will be removed soon, and I don't know how else this can be tested:

https://github.com/vuejs/vue-test-utils/问题/331

推荐答案

来自你正在努力实现的

在测试时,我想确保 externalDependency.doThing() 是用 bar(来自 vuex 状态)调用的,如下所示:

When testing, I want to ensure that externalDependency.doThing() is called with bar (which comes from the vuex state) like so:

(这确实是纯单元测试方法),您可以强制更改此观察者,这基本上是一个函数.如果计算值或数据值发生变化,则无需跟踪观察者是否发生变化 - 让 Vue 处理它.因此,要在挂载的 Vue 实例中更改观察者,只需像

(and this is indeed pure unit test approach), you can just force change of this watcher, which basically is a function. There's no need to track if watcher is changing in case of computed or data value change - let Vue handle it. So, to change a watcher in a mounted Vue instance, just call it like

wrapper.vm.$options.watch.bar.call(wrapper.vm)

其中 bar 是您的观察者的姓名.通过这种方式,您将能够测试您要测试的确切功能.

Where bar is name of your watcher. This way you will be able to test exact functionality that you're aiming to test.

来自此评论的想法 https://github.com/vuejs/vue-test-utils/issues/331#issuecomment-382037200,关于 vue-test-utils 问题,您在问题中提到.

Idea taken from this comment https://github.com/vuejs/vue-test-utils/issues/331#issuecomment-382037200, on a vue-test-utils issue, mentioned by you in a question.

这篇关于如何测试从 VueX 观察计算属性的 Vue 观察者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆