[英]Vue.js - Test a Plugin
我正在学习vue.js。 我有一个插件,看起来像这样:
源极/ myPlugin.js
const MyPlugin = {
install: function(Vue, options) {
console.log('installing my plugin');
Vue.myMethod = function() {
};
}
}
我试图用jest测试这个插件。 但是,我并不喜欢开玩笑。 此时,我的test/myPlugin.test.js
文件中还有以下内容:
测试/ 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.