Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js - Test a Plugin

I am learning vue.js. 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'm not settled on Jest. Still, at this time, I have the following in my test/myPlugin.test.js 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 via Jest, I was expecting to see "installing my plugin" in the console window. However, I do not. Instead, I see:

TypeError: Vue.myMethod is not a function

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

like image 341
user687554 Avatar asked Sep 19 '25 22:09

user687554


1 Answers

You do not typically attach methods to the Vue object in this way. In most cases you add them to the prototype.

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

Then you would call it using

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/[email protected]/dist/vue.js"></script>
like image 163
Bert Avatar answered Sep 22 '25 13:09

Bert