英文:
When using testing-library with Vue, what is the best way to confirm an element is hidden by v-show?
问题
使用 testing-library 与 Vue 一起时,轻松检查元素是否不在 DOM 中。
例如,当元素的 v-if 为 false
时:
element = screen.queryByTestId("my-element")
expect(element).toBeNull()
然而,当使用 v-show 时,元素不会从 DOM 中删除,而是通过内联样式 display: none
切换,因此上述方法不起作用。
可以像这样操作:
element = screen.queryByTestId("my-element")
expect(element.style.display).toEqual("none")
但这感觉有点脆弱。有更好的处理方法吗?
英文:
When using testing-library with Vue it is easy to check if an element is not present in the DOM.
For example when v-if for the element is false
:
element = screen.queryByTestId("my-element")
expect(element).toBeNull()
However when using v-show the element isn't removed from the DOM, it is toggled via an inline style of display: none
, so the above won't work.
I can do something like this:
element = screen.queryByTestId("my-element")
expect(element.style.display).toEqual("none")
But this feels somewhat brittle. Is there a better way to handle this?
答案1
得分: 2
从@testing-library/vue
的Quickstart中:
> 你可能也会对安装@testing-library/jest-dom感兴趣,这样你就可以使用自定义的Jest匹配器来检查DOM。
匹配器包括.toBeVisible(),描述如下:
> 这允许你检查元素是否当前对用户可见。
>
> 元素可见的条件包括:
> - 它的css属性display
不设置为none
> - 它的css属性visibility
不设置为hidden
或collapse
> - 它的css属性opacity
不设置为0
其父元素也是可见的(以此类推直到DOM树的顶部)
> - 它没有hidden
属性
> - 如果是<details />
,它有open
属性
注意:jest-dom
不关心您使用哪个框架。它评估HTML和CSS的值,不管哪个指令生成这些值。HTML和CSS输出是用户的浏览器接收到的内容。
附注:既然你提到了,检查元素是否在DOM中应该使用expect(queryBy*(*))[.not].toBeInTheDocument()
来完成。
在最新版本的@testing-library
中,其中包含非常有帮助的linting规则,建议使用getBy*
查询来断言在DOM中存在,并使用queryBy*
来断言不存在。
英文:
From @testing-library/vue
's Quickstart:
> You may also be interested in installing @testing-library/jest-dom so you can use the custom Jest matchers for the DOM.
The matchers contain .toBeVisible(), described as:
> This allows you to check if an element is currently visible to the user.
>
>An element is visible if all the following conditions are met:
> - it does not have its css property display
set to none
> - it does not have its css property visibility
set to either hidden
or collapse
> - it does not have its css property opacity
set to 0
its parent element is also visible (and so on up to the top of the DOM tree)
> - it does not have the hidden
attribute
> - if <details />
it has the open
attribute
Note: jest-dom
doesn't care what framework you use. It evaluates HTML & CSS values, regardless of what directives generate those values. HTML and CSS output is what the user's browser receives.
Side-note: since you mentioned it, checking if an element is in DOM should be done with expect(queryBy*(*))[.not].toBeInTheDocument()
.
In the latest version of @testing-library
, which contains very helpful linting rules, the recommendation is to use getBy*
queries for asserting presence in DOM and queryBy*
for asserting absence.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论