【问题标题】:How do I test the call on a Vuex Mutation in a Vue component?如何在 Vue 组件中测试对 Vuex Mutation 的调用?
【发布时间】:2021-09-21 15:12:53
【问题描述】:

假设你有一个 vue 组件,其方法如下:

methods:{
    doSomething(someParameter){
       //maybe do something with that Parameter 
       this.$store.commit("storeSomething",someParameter);

       let someParameter2 = this.transformToSth(someParameter);
       this.$store.commit("storeSomethingElse",someParameter2);
    }
}

我该怎么做才能让这种测试在 Jest 中起作用?

test("that the commit was correctly called",()=>{
     wrapper.vm.doSomething(someParameter);
     expect(wrapper.vm.$store.commit).hasBeenCalledWith(someParameter);

     expect(wrapper.vm.$store.commit).hasBeenCalledWith(someParameter2);
})

还请注意,我希望模拟也再次恢复,因此该方法使用与以前相同的实现。否则,我会在测试之间创建依赖关系,这是我非常想避免的。

(我也希望它与动作和 getter 函数的工作方式相同)

【问题讨论】:

  • 相关文档链接:Using Vue Test Utils with Vuex
  • @zcoop98 是的,我看过这个。但是,情况略有不同。文档希望或多或少地直接测试一个动作。我想在组件的方法中使用该操作时模拟该操作。但也许我忽略了什么......?

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


【解决方案1】:

所以我发现可以用 spyOn 解决这个问题:

   test("that the commit was correctly called", () => {
        let spy = jest.spyOn(userCardEditingWrapper.vm.$store, "commit");
        wrapper.vm.doSomething("test");
        expect(spy).toHaveBeenCalledWith("storeSomething", someParameter);
        expect(spy).toHaveBeenCalledWith("storeSomethingElse", someParameter2);
      });

感谢来自 Vue Discord 频道的 @devTea,它给了我 jest.fn() 的提示。

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 2021-07-27
    • 2018-04-17
    • 1970-01-01
    • 2020-03-14
    • 2020-09-30
    • 2017-09-15
    • 2022-01-26
    • 2020-06-23
    相关资源
    最近更新 更多