Skip to content

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

fix(toHaveCount): another edge case fix (#9860)

Pavel Feldman75ac579facff
diff --git a/packages/playwright-core/src/server/frames.ts b/packages/playwright-core/src/server/frames.ts
index 473b11254f..2509fdf78d 100644
--- a/packages/playwright-core/src/server/frames.ts
+++ b/packages/playwright-core/src/server/frames.ts
@@ -1183,8 +1183,9 @@ export class Frame extends SdkObject {
// expect(listLocator).toHaveCount(0) passes when there are no elements matching.
// expect(listLocator).not.toHaveCount(1) passes when there are no elements matching.
- if (options.expression === 'to.have.count')
- return { matches: options.expectedNumber === 0, received: options.expectedNumber };
+ const expectsEmptyCount = options.expectedNumber === 0;
+ if (options.expression === 'to.have.count' && expectsEmptyCount !== options.isNot)
+ return { matches: expectsEmptyCount, received: 0 };
// When none of the above applies, keep waiting for the element.
return continuePolling;
diff --git a/tests/playwright-test/playwright.expect.misc.spec.ts b/tests/playwright-test/playwright.expect.misc.spec.ts
index 4986a82ae4..be3f01eb64 100644
--- a/tests/playwright-test/playwright.expect.misc.spec.ts
+++ b/tests/playwright-test/playwright.expect.misc.spec.ts
@@ -49,6 +49,24 @@ test('should support toHaveCount', async ({ runInlineTest }) => {
await expect(locator).not.toHaveCount(1);
});
+ test('eventually pass non-zero', async ({ page }) => {
+ await page.setContent('<ul></ul>');
+ setTimeout(async () => {
+ await page.setContent("<ul><li>one</li><li>two</li></ul>");
+ }, 500);
+ const locator = page.locator('li');
+ await expect(locator).toHaveCount(2);
+ });
+
+ test('eventually pass not non-zero', async ({ page }) => {
+ await page.setContent('<ul><li>one</li><li>two</li></ul>');
+ setTimeout(async () => {
+ await page.setContent("<ul></ul>");
+ }, 500);
+ const locator = page.locator('li');
+ await expect(locator).not.toHaveCount(2);
+ });
+
test('fail zero', async ({ page }) => {
await page.setContent('<div><span></span></div>');
const locator = page.locator('span');
@@ -63,7 +81,7 @@ test('should support toHaveCount', async ({ runInlineTest }) => {
`,
}, { workers: 1 });
const output = stripAscii(result.output);
- expect(result.passed).toBe(3);
+ expect(result.passed).toBe(5);
expect(result.failed).toBe(2);
expect(result.exitCode).toBe(1);
expect(output).toContain('Expected: 0');