情况
我正在尝试 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
}
}
}
})
问题
如何安装使我们成为
$refs
的组件在 mounted
生命周期?
最佳答案
shallowMount
应该提供引用,所以this.$refs.tgmp
应该是 <div>
万一元素 <div ref="tgmp">
存在于初始渲染的 View 中。$refs
不应该被 mock ,因为它是内部属性并在组件初始化时分配。它是依赖于 ref 的计算属性,因此可以在必要时对其进行模拟,因为在 JSDOM 中元素高度应为 0:
jest.spyOn(ThePlayerBar.options.computed, 'barH').mockReturnValue(600);
或者:
wrapper = shallowMount(Bar, {
store,
computed: { barH: () => 600 }
})
关于javascript - vue-test-utils - 如何处理 $refs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61223992/