Vue.js - 测试插件



我正在学习vue.js。我有一个插件,看起来像这样:

源/我的插件.js

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

我正在尝试使用开玩笑来测试这个插件。但是,我并不满足于开玩笑。不过,目前,我的test/myPlugin.test.js文件中有以下内容:

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);        
});
});

当我通过 Jest 运行此测试时,我希望在控制台窗口中看到"安装我的插件"。但是,我没有。相反,我看到:

TypeError: Vue.myMethod is not a function

我做错了什么?我正在尝试通过一些测试设置一个基本插件。我不确定为什么这不起作用。任何帮助,不胜感激。

你通常不会以这种方式将方法附加到 Vue 对象。在大多数情况下,将它们添加到prototype中。

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

然后你会用

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>

最新更新