如何修复Playwright中的TypeError: page.locator(...).toContainText不是函数
修复Playwright中"toContainText is not a function"错误
问题原因
<meta name="description"> 元素的描述内容存储在 content 属性中,而非元素的文本内容里。toContainText 方法仅适用于检查元素内部的可见文本(如<div>、<p>等标签的文本),无法用于验证属性值,因此会抛出该错误。
修复方案
你需要通过检查content属性的值来验证元描述,以下是两种可行的方法:
方法1:使用toHaveAttribute结合字符串包含匹配
直接断言元元素的content属性包含目标文本:
import { test, expect } from '@playwright/test'; test('Landing page', async ({ page }) => { await page.goto('https://www.unient.biz/'); await page.getByRole('button', { name: 'Accept All' }).click(); const MetaDescription = page.locator("//meta[@name='description']"); // 使用expect.stringContaining检查属性值是否包含目标文本 await expect(MetaDescription).toHaveAttribute( 'content', expect.stringContaining('Empower your organisation to function onshore and offshore as one enterprise by using our versatile range of services and regional service delivery') ); });
方法2:获取属性值后单独断言
先提取content属性的值,再用toContain验证:
import { test, expect } from '@playwright/test'; test('Landing page', async ({ page }) => { await page.goto('https://www.unient.biz/'); await page.getByRole('button', { name: 'Accept All' }).click(); const MetaDescription = page.locator("//meta[@name='description']"); // 获取content属性值 const metaContent = await MetaDescription.getAttribute('content'); // 断言值包含目标文本 await expect(metaContent).toContain('Empower your organisation to function onshore and offshore as one enterprise by using our versatile range of services and regional service delivery'); });
内容的提问来源于stack exchange,提问作者Sarah G
相关产品推荐
相关产品推荐

