How to test Vue watcher that watches a computed property from VueX?

后端 未结 4 1694
一个人的身影
一个人的身影 2021-02-12 12:53

Suppose I have the following component:

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

export default {
  name: \'Foo\',
  computed:         


        
4条回答
  •  花落未央
    2021-02-12 13:21

    From you're trying to achieve

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

    (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)
    

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

    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.

提交回复
热议问题