vue-test-utils - 如何处理 $refs?

vue-test-utils - how to handle $refs?

情况

我正在尝试 shallowMount 一个组件,但没有成功。

组件利用$refs读取div的高度。该值在计算的 属性 中读取。然后在 mounted 生命周期中,我将该值保存在商店中。

逻辑本身很简单并且工作正常。但是 在测试套件中,组件的安装中断,因为 $refs 键是 undefined

明确一点:我不打算测试 $refs,我只需要安装组件并继续进行实际的单元测试。

组件

这是标记:

<div ref="tgmp">

我将 div 的高度保存在计算得到的 属性:

computed: {
  barH() {
    return this.$refs.tgmp.clientHeight
  }
}

然后,在已安装的生命周期中,我将值提交到存储中:

this.$store.commit('setBarHeight', this.barH)

测试

这是测试。我省略了不相关的东西,比如在 localVue 中安装商店。

beforeEach(() => {
  wrapper = shallowMount(Bar, {
    store,
  })
})

test('is a Vue instance', () => {
  expect(wrapper.isVueInstance()).toBeTruthy()
})

错误

Error in mounted hook: "TypeError: Cannot read property 'clientHeight' of undefined"

尝试

我一直在尝试在任何地方搜索解决方案,但找不到。 我试图模拟 $refs,但没有成功:

wrapper = shallowMount(ThePlayerBar, {
  store,
  mocks: {
    $refs: {
      tgmp: {
        clientHeight: 600
      }
    }
  }
})

问题

如何在 mounted 生命周期中安装一个使我们成为 $refs 的组件?

shallowMount 应该提供引用,所以 this.$refs.tgmp 应该是 <div> 元素,以防 <div ref="tgmp"> 存在于初始渲染的视图中。

$refs 不应该被模拟,因为它是内部的 属性 并且在组件初始化时分配。它的计算 属性 依赖于 ref,因此如果需要可以模拟它,因为在 JSDOM 中元素高度预计为 0:

jest.spyOn(ThePlayerBar.options.computed, 'barH').mockReturnValue(600);

或:

  wrapper = shallowMount(Bar, {
    store,
    computed: { barH: () => 600 }
  })