[英]vue-test-utils - how to handle $refs?
THE SITUATION情况
I am trying to shallowMount
a component, unsuccessfully.我正在尝试对组件进行shallowMount
安装,但未成功。
The component makes use of $refs
to read the height of a div
.该组件使用$refs
来读取div
的高度。 That value is read inside a computed property.该值在计算属性中读取。 Then in the mounted
lifecycle I save that value in the store.然后在mounted
的生命周期中,我将该值保存在商店中。
The logic itself is simple and works fine.逻辑本身很简单并且工作正常。 But in the test suite, the mounting of the component breaks, because the $refs
key is undefined
.但是在测试套件中,组件的安装中断,因为$refs
键是undefined
。
To be clear: I don't intend to test the $refs
, I just need to mount the component and move on doing actual unit-testing.明确一点:我不打算测试$refs
,我只需要安装组件并继续进行实际的单元测试。
THE COMPONENT组件
This is the markup:这是标记:
<div ref="tgmp">
I save the height of the div in a computed property:我将 div 的高度保存在计算属性中:
computed: {
barH() {
return this.$refs.tgmp.clientHeight
}
}
And then, in the mounted lifecycle, I commit the value in the store:然后,在挂载的生命周期中,我提交存储中的值:
this.$store.commit('setBarHeight', this.barH)
THE TEST考试
This is the test.这是测试。 I have omitted irrelevant stuff, like installing the store in the localVue.我省略了不相关的东西,比如在 localVue 中安装商店。
beforeEach(() => {
wrapper = shallowMount(Bar, {
store,
})
})
test('is a Vue instance', () => {
expect(wrapper.isVueInstance()).toBeTruthy()
})
THE ERROR错误
Error in mounted hook: "TypeError: Cannot read property 'clientHeight' of undefined"
ATTEMPT试图
I have been trying searching anywhere for a solution, but couldn't find it.我一直在尝试在任何地方寻找解决方案,但找不到。 I have tried to mock the $refs, but without success:我试图模拟 $refs,但没有成功:
wrapper = shallowMount(ThePlayerBar, {
store,
mocks: {
$refs: {
tgmp: {
clientHeight: 600
}
}
}
})
THE QUESTION问题
How can I mount a component that makes us of $refs
in the mounted
lifecycle?如何在mounted
的生命周期中挂载使我们使用$refs
的组件?
shallowMount
is supposed to provide refs, so this.$refs.tgmp
should be <div>
element in case <div ref="tgmp">
exists in the view on initial render. shallowMount
应该提供 refs,所以this.$refs.tgmp
应该是<div>
元素,以防<div ref="tgmp">
存在于初始渲染的视图中。
$refs
isn't supposed to be mocked because it's internal property and assigned on component initialization. $refs
不应该被嘲笑,因为它是内部属性并在组件初始化时分配。 It's computed property that relies on a ref, so it can be mocked if necessary because element height is expected to be 0 in JSDOM:它是依赖于 ref 的计算属性,因此可以在必要时对其进行模拟,因为在 JSDOM 中元素高度应为 0:
jest.spyOn(ThePlayerBar.options.computed, 'barH').mockReturnValue(600);
Or:或者:
wrapper = shallowMount(Bar, {
store,
computed: { barH: () => 600 }
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.