Search code examples
vue.jsjestjsvue-test-utils

Vue Test Utils - Skip created hook


I want to skip all of the methods that are being called within the created() hook. Is there a way to do this?

So instead of this

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

I want this

created() { }

It's worth noting, I cannot actually change the component itself, but for testing purposes, this needs to be done.


Solution

  • You can accomplish this with a global mixin (see https://v2.vuejs.org/v2/guide/mixins.html#Global-Mixin)

    However, for your case you need a custom merge strategy to prevent the created hook on the component from being run:

    Hook functions with the same name are merged into an array so that all of them will be called. Mixin hooks will be called before the component’s own hooks. (https://v2.vuejs.org/v2/guide/mixins.html#Option-Merging)

    See a working example at 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")
      }
    })