Home > other >  Run assertions directly in browser context in Playwright
Run assertions directly in browser context in Playwright

Time:03-27

I would like to test some apis which are tied directly into browser and not necessary have UI representation.

Simpliest test beeing something like:

import { test, expect } from "@playwright/test";

test("creates Image element", async ({ page }) => {
  await page.goto(`http://localhost:3333/e2e/assets/Dynamic.spec.html`);

  const img = new Image();
  const asset = new DynamicAsset(img);

  expect(asset.element()).toEqual(img);
});

When using cypress, all the tests are run in browser context. What would work.

But in playwright following error occurs:

ReferenceError: Image is not defined

    at file:///Users/tomche/development/frontendara/amandes/e2e/assets/Dynamic.spec.js:6:15

And if using page.evaluate like:

import { test, expect } from "@playwright/test";

test("creates Image element", async ({ page }) => {
  await page.goto(`http://localhost:3333/e2e/assets/Dynamic.spec.html`);

  await page.evaluate(() => {
    const img = new Image();
    const asset = new DynamicAsset(img);

    expect(asset.element()).toEqual(img);
  });
});

Error is:

page.evaluate: ReferenceError: expect is not defined

Which is happening since code evaluated in browser context doesn't have imports from upper scope.

Documentation seems to mention only things which are serialisable, but this code needs complex things to be verified which are not really mockable in node or serilasible.

So is there a way to run assertions inside the browser similar to cypress/karma etc.?

CodePudding user response:

Running full test code as updated, can get expect to work outside of evaluate()

(But note I have a different error message from original)

import { test, expect } from "@playwright/test";

test("creates Image element", async ({ page }) => {
  await page.goto(`http://localhost:3333/e2e/assets/Dynamic.spec.html`);

  const result = await page.evaluate(() => {
    const img = new Image();
    const asset = new DynamicAsset(img);
    return {img, asset}
  });

  expect(result.asset.element()).toEqual(result.img);
});

CodePudding user response:

Pass expect into page.evaluate()

import { test, expect } from "@playwright/test";

test("creates Image element", async ({ page }) => {
  await page.goto(`http://localhost:3333/e2e/assets/Dynamic.spec.html`);

  await page.evaluate((expect) => {
    const img = new Image();
    const asset = new DynamicAsset(img);

    expect(asset.element()).toEqual(img);
  }, expect);
});
  • Related