如何设置或测试此.$ parent在VUEJS单元测试中



在我的组件集中

data(){
categories: this.$parent.categories => which I set in main.js
}

代码文件main.js

import categories from '../config/categories';
new Vue({
    router,
    data: {
        categories: categories
}
});

我创建了1个功能单元测试

it(‘check component is a button’,() => {
const wrapper = shallow(FormSearch);
expect(wrapper.contains(‘button’)).toBe(true);
});

i运行测试,然后显示错误:data((中的错误:" TypeError:无法读取未定义的属性'类别'如何修复它。帮助我。

为什么不导入您的类别配置文件直接为组件?

import Categories from '../config/categories'

然后您的数据方法可以直接访问它:

data () { return { categories: Categories }}

您会发现测试要容易得多

是的,谢谢。我变了。我进行测试,然后发生错误其他

Cannot find module '../../config/categories' from 'mycomponet.vue'.

虽然。我在浏览器上运行项目,只是运行良好。如何修复它。非常感谢您

用于测试,您可以在测试时设置模拟数据以逃避undefined错误。但这不是标准解决方案.....

it(‘check component is a button’,() => {
   const wrapper = shallow(FormSearch);
   let mockCategories = { // mock category data }
   wrapper.$parent = {
     categories: mockCategories
   }
   expect(wrapper.contains(‘button’)).toBe(true);
});

尝试以下方法:

const Parent = {
  data: () => ({
    val: true
  }),
  template: '<div />'
}
const wrapper = shallowMount(TestComponent, {
  parent: Parent
})

最新更新