【问题标题】:Mock of store action of vuex does not mockedvuex store action的mock不mock
【发布时间】:2021-07-09 13:28:56
【问题描述】:

我有一个小的 vue 组件,它在创建的钩子上调度一些动作

@Component
export default class SomeComponent extends Vue {
  created() {
    store.dispatch('module/myAction', { root: true });
  }
}

我写了下一个测试

    const localVue = createLocalVue();
localVue.use(Vuex);
localVue.use(VueRouter);
const localRouter = new VueRouter();
describe('SomeComponent.vue Test', () => {
  let store: any;

  beforeEach(() => {
    store = new Vuex.Store({
      modules: {
        module: {
          namespaced: true,
          actions: {
            myAction: jest.fn()
          }
        }
      }
    });
  });
  it('is component created', () => {
    const wrapper = shallowMount(SomeComponent, {
      localVue,
      store,
      propsData: {}
    });

    expect(wrapper.isVueInstance()).toBeTruthy();
  });
});

但由于某种原因,“真实”代码被执行,我收到了警告

【问题讨论】:

    标签: vue.js jestjs vuex vue-test-utils


    【解决方案1】:

    isVueInstance() 已弃用。在您的测试中,您应该模拟 $store 对象和它的 dispatch 函数。我修正了 created() 中的错字,这是我的 SomeComponent 版本和工作测试,希望对您有所帮助。

    
    @Component
    export default class SomeComponent extends Vue {
      created () {
        this.$store.dispatch('module/myAction', { root: true })
      }
    }
    
    import { shallowMount, Wrapper } from '@vue/test-utils'
    import SomeComponent from '@/components/SomeComponent/SomeComponent.vue'
    
    let wrapper: Wrapper<SomeComponent & { [key: string]: any }>
    
    describe('SomeComponent.vue Test', () => {
      beforeEach(() => {
        wrapper = shallowMount(SomeComponent, {
          mocks: {
            $store: {
              dispatch: jest.fn()
            }
          }
        })
      })
      it('is component created', () => {
        expect(wrapper.vm.$store.dispatch).toBeCalled()
        expect(wrapper.vm.$store.dispatch).toBeCalledWith('module/myAction', { root: true })
      })
    })
    

    另外请记住,当您测试 SomeComponent 或任何其他不应该测试存储功能的组件时,您应该只测试使用某些参数调用某些操作/突变。商店应单独测试。因此,您在测试组件时不需要创建真正的 Vuex Store,只需要模拟 $store 对象即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-04
      • 1970-01-01
      • 2017-06-30
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多