DEV Community

neuralbyte
neuralbyte

Posted on

Test a Cloud Browser Workflow Locally Before You Compare Providers

A screenshot can show a real product and the wrong offer. This regularly starts with a script that waits for navigation, clicks a variant, and captures the page before the price updates. Give the browser test an explicit acceptance rule and make it prove that rule before saving evidence.

The example below runs a local Playwright fixture with no external requests. You can take the acceptance logic to a managed browser after you've tested the state change.

Decide what the artifact has to prove

For a product variant, verify the selected control, model, currency, visible price and availability. Capture the offer container after the assertions pass. Store a small structured record beside the PNG. Include a label for synthetic runs, plus the accepted source URL and UTC time for real captures.

A single timestamp or screenshot is a weak way to compare runs. A JSON record makes it possible to filter for the intended state, and a digest lets a reviewer check that the screenshot still matches the attached file. Capture only the region and fields you need.

Run the screenshot fixture locally

Use Node.js 22 and Playwright's Chromium runtime. Set this up in a new directory:

npm install playwright-core@1.65.1
npx playwright-core install chromium
Enter fullscreen mode Exit fullscreen mode

Save the following as visual-evidence.mjs. The fixture starts on Silver and uses a timer to update the variant and price after selecting Black. The amounts are synthetic.

import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { chromium } from 'playwright-core';

const fixture = `
<!doctype html>
<meta charset="utf-8">
<title>Offer state fixture</title>
<style>main {max-width: 32rem; padding: 2rem; font: 18px system-ui}</style>
<main data-offer data-variant="Silver" data-currency="USD">
  <h1>Demo headphones</h1>
  <button type="button" aria-pressed="false">Black</button>
  <p data-price>199.00</p>
  <p data-stock>In stock</p>
</main>
<script>
  const button = document.querySelector('button');
  button.addEventListener('click', () => {
    window.setTimeout(() => {
      button.setAttribute('aria-pressed', 'true');
      const offer = document.querySelector('[data-offer]');
      offer.dataset.variant = 'Black';
      offer.querySelector('[data-price]').textContent = '179.00';
    }, 100);
  });
</script>`;

async function collectOffer(page) {
  const offer = page.locator('[data-offer]');
  const button = offer.getByRole('button', { name: 'Black', exact: true });
  await button.click({ timeout: 2000 });
  const selected = page.locator('[data-offer][data-variant="Black"]');
  await selected.locator('button[aria-pressed="true"]').waitFor({ timeout: 2000 });

  const data = {
    variant: await selected.getAttribute('data-variant'),
    currency: await selected.getAttribute('data-currency'),
    price: (await selected.locator('[data-price]').innerText()).trim(),
    availability: (await selected.locator('[data-stock]').innerText()).trim(),
  };
  assert.deepEqual(data, {
    variant: 'Black', currency: 'USD', price: '179.00', availability: 'In stock',
  });
  const image = await selected.screenshot({ timeout: 2000 });
  assert(image.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')));
  return { data, image };
}

const output = process.argv[2] || 'output';
const browser = await chromium.launch({ headless: true, timeout: 15000 });
try {
  const page = await browser.newPage({ viewport: { width: 960, height: 700 } });
  // Use an in-memory fixture. Reject any external subresource.
  await page.route('**/*', route => route.abort());
  await page.setContent(process.argv.includes('--missing-variant')
    ? fixture.replace('>Black</button>', '>Unavailable</button>')
    : fixture);
  const { data, image } = await collectOffer(page);
  const report = {
    source: 'synthetic-local-fixture',
    ...data,
    bytes: image.length,
    sha256: createHash('sha256').update(image).digest('hex'),
  };
  await mkdir(output, { recursive: true });
  await writeFile(join(output, 'offer.png'), image);
  await writeFile(join(output, 'offer.json'), `${JSON.stringify(report, null, 2)}\n`);
  console.log(JSON.stringify(report));
} catch (error) {
  if (error.name !== 'TimeoutError') throw error;
  console.error('Variant or offer state was not ready within the expected time.');
  process.exitCode = 1;
} finally {
  await browser.close();
}
Enter fullscreen mode Exit fullscreen mode

Run both the happy path and the negative control:

node visual-evidence.mjs output-ok
node visual-evidence.mjs output-missing --missing-variant
Enter fullscreen mode Exit fullscreen mode

The first command records Black at synthetic USD 179.00, writes offer.json and a PNG, and prints the evidence summary. The second command intentionally exits with code 1 when the Black control is unavailable. It writes no new artifact. Use different output directories so a failed run can't be confused with a screenshot already saved by a successful run.

A production page can redraw fields across separate events. Wait for the stable selected state and the specific offer value you need when those updates are independent. Also confirm that the correct container is still visible at capture time.

Move the same assertions to a cloud browser

A hosted browser changes how you obtain a context. The product-level acceptance rule stays the same. Nstdata Cloud Browser's lifecycle documentation covers creating a session, waiting for ready, and getting a short-lived CDP endpoint and authentication headers.

Attach with Playwright's Chromium client using chromium.connectOverCDP(cdpUrl, { headers }). Verify the context and page before running the offer assertions. Attach to a controlled test session first. Keep issued connection credentials out of logs and artifacts. When done, disconnect the client, stop the cloud session by its ID, and verify ended. A disconnect and a stopped session are separate events. Playwright's CDP documentation

A provider evaluation should track these separately:

Measurement What to record
Provisioning Request ID, elapsed setup time, ready state and effective configuration.
Browser work Time to the accepted state, variant checks, evidence files and diagnostics.
Cleanup Session ID, stop result, and whether the session reached the terminal state.
Costs Billable runtime, traffic, failed attempts and reviewer time.

Give routine fetches a smaller execution path

Use a request-based tool when known URLs and documented rendering options already yield the required content. Nstdata Crawl returns artifacts such as Markdown, HTML or screenshots. It can serve the routine evidence path. Keep Playwright for authorized interactions that require an explicit browser state and assertions.

The local fixture verifies the assertions and artifact-writing logic. Use the same controlled case to compare hosted providers, then repeat it on a representative authorized target. That separates connection behavior from the accuracy of your extraction rules.

Top comments (0)