情况
我正在尝试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的组件?
发布于 2020-04-15 11:11:06
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 }
})https://stackoverflow.com/questions/61223992
复制相似问题