首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >vuex的store action的Mock不被Mock

vuex的store action的Mock不被Mock
EN

Stack Overflow用户
提问于 2021-04-14 21:27:21
回答 1查看 36关注 0票数 0

我有一个小的vue组件,在钩子上创建了一些分派一些操作

代码语言:javascript
运行
复制
@Component
export default class SomeComponent extends Vue {
  created() {
    store.dispatch('module/myAction', { root: true });
  }
}

我写了下一个测试

代码语言:javascript
运行
复制
    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();
  });
});

但是由于某些原因,“真正的”代码被执行了,我得到了一个警告

EN

回答 1

Stack Overflow用户

发布于 2021-04-21 15:16:00

isVueInstance()已弃用。在您的测试中,您应该模拟$store对象及其调度函数。我修复了created()中的拼写错误,这是我的SomeComponent和工作测试版本,希望能有所帮助。

代码语言:javascript
运行
复制
@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对象。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67092731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档