【问题标题】:Vue Test Utils - Skip created hookVue Test Utils - 跳过创建的钩子
【发布时间】:2019-11-19 03:28:12
【问题描述】:

我想跳过在created() 挂钩中调用的所有方法。有没有办法做到这一点?

所以不是这个

        created() {
            this.getAllocations();
            this.getModels();
            this.getTeams();
            this.getCustodians();
            this.getDefaultFeeStructure();
        }

我想要这个

created() { }

值得注意的是,我实际上无法更改组件本身,但出于测试目的,需要这样做。

【问题讨论】:

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


    【解决方案1】:

    您可以使用全局 mixin 来完成此操作(请参阅 https://vuejs.org/v2/guide/mixins.html#Global-Mixin

    但是,对于您的情况,您需要一个自定义合并策略来防止在组件上创建的钩子运行:

    将同名的钩子函数合并到一个数组中,这样所有的钩子函数都会被调用。 Mixin 钩子会在组件自己的钩子之前被调用。 (https://vuejs.org/v2/guide/mixins.html#Option-Merging)

    https://jsfiddle.net/rushimusmaximus/9akf641z/3/查看一个工作示例

    Vue.mixin({
      created() {
        console.log("created() in global mixin")
      }
    });
    
    const mergeCreatedStrategy = Vue.config.optionMergeStrategies.created;
    Vue.config.optionMergeStrategies.created = (parent, child) => {
      return mergeCreatedStrategy(parent);
    };
    
    new Vue ({
      el: "#vue-app",
      template: '<p>See console output for logging. Rendered at {{renderDate}}</p>',
      data() {
        return {
         renderDate: new Date()
        }
      },
      created() {
        console.log("created() in component")
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2019-01-18
      • 2020-02-13
      • 2019-09-26
      • 2020-12-01
      • 1970-01-01
      • 2019-03-13
      • 2019-10-24
      • 2019-02-15
      • 2021-04-03
      相关资源
      最近更新 更多