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

后端 未结 4 1693
一个人的身影
一个人的身影 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 12:56

    The Vue Test Utils documentation points at a different approach where you use a very simple Vuex store:

    import { shallowMount, createLocalVue } from '@vue/test-utils'
    import Vuex from 'vuex'
    
    // use a localVue to prevent vuex state from polluting the global Vue instance
    const localVue = createLocalVue();
    localVue.use(Vuex);
    
    describe('Foo.vue', () => {
      let state;
      let store;
    
      beforeEach(() => {
        // create a new store for each test to prevent pollution
        state = { bar: 'bar' };
        store = new Vuex.Store({ state });
      })
    
      it('should call externalDependency.doThing with bar', () => 
      {
        shallowMount(MyComponent, { store, localVue });
        const spy = jest.spyOn(externalDependency, 'doThing');
        // trigger the watch
        state.bar = 'baz';
        expect(spy).toHaveBeenCalledWith('baz');
      });
    })
    

提交回复
热议问题