【问题标题】:How to set grandparent mock data for vue unit test如何为 vue 单元测试设置祖父母模拟数据
【发布时间】:2022-08-06 09:15:05
【问题描述】:

我正在为现有的 vue 组件编写单元测试。该组件有一个在安装时运行的方法。该方法使用return this.$parent.$parent.someData。我正在寻找一种在编写单元测试时将祖父母模拟数据传递给组件的方法。我知道将父组件作为模拟传递的方法,但正在寻找一种传递祖父母的方法。

我在测试中使用以下代码

const wrapper = shallowMount(MyComponent,{
   parentComponent:ParentComponent
})

寻找一种传递祖父母组件的方法。我正在使用 vue-test-utils。

PS:我无法对现有代码进行更改

    标签: vue.js unit-testing vue-test-utils


    【解决方案1】:

    这是最直接的方法:

    import Child from './path/to/Child.vue'
    
    const GP = shalowMount({
      template: '<div />',
      data: () => ({
        foo: 'bar' // mocked data
      })
    })
    
    const wrapper = shallowMount(Child, {
      parentComponent: {
        created() {
          this.$parent = GP.vm
        }
      }
    })
    
    console.log(wrapper.vm.$parent.$parent.foo) // bar
    

    如果您希望实现更接近用户在浏览器中看到的内容,这也应该有效(取决于GrandParentParent deps:商店、第三方包等...):

    import GrandParent from './path/to/GrandParent.vue'
    import Parent from './path/to/Parent.vue'
    import Child from './path/to/Child.vue'
    
    const GP = shallowMount(GrandParent);
    /* set GP data, props, mocks or spies */
    
    const wrapper = shallowMount(Child, {
      parentComponent: shallowMount(Parent, {
        parentComponent: GP.vm
      }).vm
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-07
      • 2018-11-03
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2017-11-14
      • 2017-12-05
      相关资源
      最近更新 更多