我开始使用 Vue.js 并且很难找到关于单元测试 的文档。
我正在尝试测试组件 methods
和内置的东西作为 ready()
。我可以正确地调用它们,但它们在内部引用了 this
对象,并且 this
上下文在测试期间丢失了。
错误
TypeError: this.$on 不是函数
spec.js
import Vue from 'vue';
import Partners from 'components/main/partner/Partners';
describe.only('Partners.vue', () => {
it('should render with mocked partners', (cb) => {
Partners.ready(); // I get an error here because ready() is calling inside: this.$on(...)
cb(null);
});
});
component.vue
export default {
name: 'Partners',
data() {
return { };
},
methods: {
get() {
// ...
}
},
ready() {
this.$on('confirm', (confirm) => {
// ...
});
this.get();
}
};
最佳答案
我认为 ready() 与 Vue 1.0 一起贬值了。考虑升级到 Vue 2(其中 mounted() 替换了 ready())。
要测试您的组件,您需要初始化您的组件和一个 Vue 实例(并且通常会挂载它,具体取决于您在做什么)。
使用 vue-webpack 模板(使用 Vue 2):
var ctor = Vue.extend(Partners)
var vm = new ctor()
vm.$mount()
现在你可以做vm.method(),vm.mount()会自动被调用等等。
关于javascript - 测试 Vue 组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37893456/