`await expect.element(page).not.toHaveTextContent()`
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
- [x] Follow our Code of Conduct
- [x] Read the Contributing Guidelines.
- [x] Read the docs.
- [x] Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
could you do this?
await expect.element(document.body).not.toHaveTextContent()
since tests run in the browser, i believe this should work
@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:
- Add
page.body()or similar which returns a locator - Make the value to
toHaveTextContentoptional so that.toHaveTextContent()and.not.toHaveTextContent()work
Can't you pass in some text content that you know you don't want to be there?
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.
As a workaround, these two seem to work:
await expect.element(document.body).toHaveTextContent(/^$/);
await expect.element(document.body).toBeEmptyDOMElement();
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.
I view it differently: toHaveTextContent() -> the element has some text, not.toHaveTextContent() -> the element does not have any text
Fair point. That reads more naturally. Going with your version: toHaveTextContent() passes when the element has text, .not.toHaveTextContent() when it's empty.