Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

fix(matchers): toHaveClass on SVG elements (#15267)

Max Schmitt71fc53bbf8c9
diff --git a/packages/playwright-core/src/server/injected/injectedScript.ts b/packages/playwright-core/src/server/injected/injectedScript.ts
index 013ce97239..10997c4297 100644
--- a/packages/playwright-core/src/server/injected/injectedScript.ts
+++ b/packages/playwright-core/src/server/injected/injectedScript.ts
@@ -1071,7 +1071,7 @@ export class InjectedScript {
if (expression === 'to.have.attribute') {
received = element.getAttribute(options.expressionArg) || '';
} else if (expression === 'to.have.class') {
- received = element.className;
+ received = element.classList.toString();
} else if (expression === 'to.have.css') {
received = window.getComputedStyle(element).getPropertyValue(options.expressionArg);
} else if (expression === 'to.have.id') {
@@ -1112,7 +1112,7 @@ export class InjectedScript {
if (expression === 'to.have.text.array' || expression === 'to.contain.text.array')
received = elements.map(e => options.useInnerText ? (e as HTMLElement).innerText : e.textContent || '');
else if (expression === 'to.have.class.array')
- received = elements.map(e => e.className);
+ received = elements.map(e => e.classList.toString());
if (received && options.expectedText) {
// "To match an array" is "to contain an array" + "equal length"
diff --git a/tests/playwright-test/playwright.expect.misc.spec.ts b/tests/playwright-test/playwright.expect.misc.spec.ts
index 7c2fea0726..12e8adf225 100644
--- a/tests/playwright-test/playwright.expect.misc.spec.ts
+++ b/tests/playwright-test/playwright.expect.misc.spec.ts
@@ -216,6 +216,11 @@ test('should support toHaveClass', async ({ runInlineTest }) => {
await expect(locator).toHaveClass('foo bar baz');
});
+ test('pass with SVGs', async ({ page }) => {
+ await page.setContent(\`<svg class="c1 c2" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"></svg>\`);
+ await expect(page.locator('svg')).toHaveClass(/c1/);
+ });
+
test('fail', async ({ page }) => {
await page.setContent('<div class="bar baz"></div>');
const locator = page.locator('div');
@@ -226,7 +231,7 @@ test('should support toHaveClass', async ({ runInlineTest }) => {
const output = stripAnsi(result.output);
expect(output).toContain('expect(locator).toHaveClass');
expect(output).toContain('Expected string: \"foo bar baz\"');
- expect(result.passed).toBe(1);
+ expect(result.passed).toBe(2);
expect(result.failed).toBe(1);
expect(result.exitCode).toBe(1);
});