Vue.js - Check Plugin

I study ... I have a plugin that looks like this:

source / myPlugin.js

const MyPlugin = {
  install: function(Vue, options) {
    console.log('installing my plugin');

    Vue.myMethod = function() {
    };
  }
}

      

I am trying to test this plugin using jest. However, I have not settled in Jest. However, at this time, I test/myPlugin.test.js

have the following in my file :

Test / myPlugin.test.js

const Vue = require('vue/dist/vue');
const MyPlugin = require('../source/myPlugin');

Vue.use(MyPlugin);

describe('MyPlugin', () => {
    let vm;

    beforeEach(() => {
        const template = `<div id="app"></div>`;
        vm = new Vue({
            template
        }).$mount();
    });

    it('should run', () => {
        Vue.myMethod();
        expect(true).toEqual(true);        
    });
});

      

When I run this test through Jest, I expected to see "installing my plugin" in the console window. However, I don't. Instead, I see:

TypeError: Vue.myMethod is not a function

      

What am I doing wrong? I am trying to install a basic plugin with some tests. I'm not sure why this isn't working. Any help is appreciated.

+3


source to share


1 answer


You usually don't attach methods to a Vue object. In most cases, you add them to prototype

.

Vue.prototype.myMethod = function() {};

      

Then you call it with



vm.myMethod()

      

console.clear()

const MyPlugin = {
  install: function(Vue, options) {
    console.log('installing my plugin');

    Vue.prototype.myMethod = function() {
      console.log("method called")
    };
  }
}
Vue.use(MyPlugin);

const template = `<div id="app"></div>`;
vm = new Vue({
  template
}).$mount();

vm.myMethod();
      

<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
      

Run codeHide result


+2


source







All Articles