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

Fra*_*ssi 6 javascript unit-testing vue.js jestjs vue-test-utils

情况

我正在尝试shallowMount一个组件,未成功。

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

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

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

组件

这是标记:

<div ref="tgmp">
Run Code Online (Sandbox Code Playgroud)

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

computed: {
  barH() {
    return this.$refs.tgmp.clientHeight
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,在挂载的生命周期中,我在商店中提交值:

this.$store.commit('setBarHeight', this.barH)
Run Code Online (Sandbox Code Playgroud)

考试

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

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

test('is a Vue instance', () => {
  expect(wrapper.isVueInstance()).toBeTruthy()
})
Run Code Online (Sandbox Code Playgroud)

错误

Error in mounted hook: "TypeError: Cannot read property 'clientHeight' of undefined"
Run Code Online (Sandbox Code Playgroud)

类型错误:无法读取未定义的属性“clientHeight”

试图

我一直在尝试在任何地方寻找解决方案,但找不到。我试图嘲笑 $refs,但没有成功:

wrapper = shallowMount(ThePlayerBar, {
  store,
  mocks: {
    $refs: {
      tgmp: {
        clientHeight: 600
      }
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

问题

我怎样才能挂载一个让我们$refs进入mounted生命周期的组件?

Est*_*ask 6

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

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

jest.spyOn(ThePlayerBar.options.computed, 'barH').mockReturnValue(600);
Run Code Online (Sandbox Code Playgroud)

或者:

  wrapper = shallowMount(Bar, {
    store,
    computed: { barH: () => 600 }
  })
Run Code Online (Sandbox Code Playgroud)