When using testing-library with Vue, what is the best way to confirm an element is hidden by v-show?

790 Views Asked by At

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

There are 1 best solutions below

1
tao On

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.