vitest-5-0-0-7-b
Claude Code's read-only tools, web search on, ludion sync off
Question
How do I check that an element's text contains a phrase in Vitest browser mode?
Answer key
- A correct answer says
- toHaveTextContent now matches strictly; use the new toMatchTextContent for partial matching.
- The stale answer
- toHaveTextContent('foo') passes when the text merely contains 'foo'.
Answer
Use the `toHaveTextContent` matcher with `expect.element`. Given a string, it passes if the element's text contains that string anywhere, so a partial phrase is enough:
```ts
import { expect, test } from 'vitest'
import { page } from 'vitest/browser' // older versions: '@vitest/browser/context'
test('shows welcome', async () => {
await expect.element(page.getByRole('heading')).toHaveTextContent('Welcome back')
// or use a regex for case-insensitive matching:
await expect.element(page.getByTestId('msg')).toHaveTextContent(/welcome back/i)
})
```
`expect.element` keeps retrying the check until it passes or times out, which suits text that renders asynchronously. To use the negative form, write `.not.toHaveTextContent(...)`.Grade
wrong
The judge's reason: It claims toHaveTextContent passes on partial matches, which is the stale behavior, and never mentions toMatchTextContent.
Session log
Agent
Use the `toHaveTextContent` matcher with `expect.element`. Given a string, it passes if the element's text contains that string anywhere, so a partial phrase is enough: ```ts import { expect, test } from 'vitest' import { page } from 'vitest/browser' // older versions: '@vitest/browser/context' test('shows welcome', async () => { await expect.element(page.getByRole('heading')).toHaveTextContent('Welcome back') // or use a regex for case-insensitive matching: await expect.element(page.getByTestId('msg')).toHaveTextContent(/welcome back/i) }) ``` `expect.element` keeps retrying the check until it passes or times out, which suits text that renders asynchronously. To use the negative form, write `.not.toHaveTextContent(...)`.