vitest icon indicating copy to clipboard operation
vitest copied to clipboard

`await expect.element(page).not.toHaveTextContent()`

Open KieranP opened this issue 1 year ago • 8 comments

Clear and concise description of the problem

When testing components, it is currently not possible to check that the rendering is empty (some of our components have conditions, and might not render anything.

expect.element(page) doesn't work because page is not a locator.

But I can't use page.getBy.... because there is nothing to get...

Suggested solution

await expect.element(page).not.toHaveTextContent()

Alternative

No response

Additional context

No response

Validations

KieranP avatar Nov 11 '25 02:11 KieranP

could you do this?

await expect.element(document.body).not.toHaveTextContent()

since tests run in the browser, i believe this should work

Georgegriff avatar Nov 11 '25 17:11 Georgegriff

@Georgegriff Yes, document.body could work (though it doesn't seem ideal when all other code is using locators). The other issue here is that toHaveTextContent() must have a value passed in. So await expect.element(document.body).not.toHaveTextContent() doesn't work.

Ideally Vitest would:

  1. Add page.body() or similar which returns a locator
  2. Make the value to toHaveTextContent optional so that .toHaveTextContent() and .not.toHaveTextContent() work

KieranP avatar Nov 11 '25 19:11 KieranP

Can't you pass in some text content that you know you don't want to be there?

Georgegriff avatar Nov 11 '25 19:11 Georgegriff

If I did .not.toHaveTextContent('Hello'), but the output had "goodbye", then the test would pass. I need to check that the result is completely blank.

KieranP avatar Nov 11 '25 19:11 KieranP

As a workaround, these two seem to work:

  await expect.element(document.body).toHaveTextContent(/^$/);
  await expect.element(document.body).toBeEmptyDOMElement();

nstepien avatar Feb 04 '26 13:02 nstepien

I want to take it.

Proposed shape: make the text argument optional, so toHaveTextContent() asserts that the element has no text content, and .not.toHaveTextContent() asserts that it has some. toHaveTextContent('') already behaves that way, so it's only a default in the matcher, plus types, docs, and a test. page.elementLocator(document.body) covers the "page is not a locator" part.

Shout if you'd rather a different shape, otherwise I'll open a PR.

nomadical avatar Sep 30 '26 08:09 nomadical

I view it differently: toHaveTextContent() -> the element has some text, not.toHaveTextContent() -> the element does not have any text

nstepien avatar Sep 30 '26 22:09 nstepien

Fair point. That reads more naturally. Going with your version: toHaveTextContent() passes when the element has text, .not.toHaveTextContent() when it's empty.

nomadical avatar Oct 01 '26 09:10 nomadical