Skip to content

Testing your Scraper

Run the Scraper against a fake site with the test kit, and prove both its items and its failures without touching the network.

A Scraper's tests never call the real site. The site can change, slow down or block you, and a test that depends on it tells you nothing about your code.

Instead, a test replaces the Capability. QuotesApiLive needs an HttpClient, so the test hands it one that answers from memory. Everything else is the real code path: the test runs the Scraper through Scraper.run, the same function an instance uses.

The domain SDK's test kit has both pieces.

PieceJob
FakeSite.make(routes)An HttpClient that answers from a map of URLs and records every URL it was asked for.
ScraperTest.run(Definition, input)Runs the Scraper once and returns the items it delivered and the failure it ended with.

Prove the items ​

Pick inputs where a wrong implementation gives a different answer. Here the fake site has three pages and the caller asks for two. An implementation that ignores maxPages, or that stops one page early, fails this test.

Example (Pagination follows has_next and stops at maxPages, in test/acceptance.test.ts)

ts
import { expect, it } from "@effect/vitest";
import { FakeSite, ScraperTest } from "@scwrap/domain/testing";
import { Effect, Layer } from "effect";

import { Quotes, QuotesApiLive, quotesOrigin } from "../src/index.js";

const page = (number: number, hasNext: boolean) =>
  JSON.stringify({
    has_next: hasNext,
    quotes: [
      {
        author: { name: `Author ${number}` },
        tags: ["first", "second"],
        text: `Quote ${number}`,
      },
    ],
  });

const url = (number: number) => `${quotesOrigin}/api/quotes?page=${number}`;

it.effect("follows has_next and stops at maxPages", () =>
  Effect.gen(function* followsPages() {
    const site = yield* FakeSite.make({
      [url(1)]: page(1, true),
      [url(2)]: page(2, true),
      [url(3)]: page(3, false),
    });

    const run = yield* ScraperTest.run(Quotes, { maxPages: 2 }).pipe(
      Effect.provide(QuotesApiLive.pipe(Layer.provide(site.layer)))
    );

    expect(run.failure).toBeNull();
    expect(yield* site.requests).toStrictEqual([url(1), url(2)]);
    expect(run.items).toStrictEqual([
      { author: "Author 1", tags: ["first", "second"], text: "Quote 1" },
      { author: "Author 2", tags: ["first", "second"], text: "Quote 2" },
    ]);
  })
);

it.effect comes from @effect/vitest. It runs the Effect for you, so a test never calls Effect.runPromise.

Layer.provide(site.layer) is the only difference from the script in the previous guide, which used FetchHttpClient.layer.

The input and the result are typed by the Definition. { maxPage: 2 } does not compile, and run.items is an array of quotes.

Prove the failures ​

A Scraper's failures are part of its contract. Test each one the site can cause. In a route, a number is a status with an empty body.

Example (A refused page fails the Run and keeps earlier items)

ts
it.effect("keeps delivered quotes when a later page is refused", () =>
  Effect.gen(function* partialRun() {
    const site = yield* FakeSite.make({
      [url(1)]: page(1, true),
      [url(2)]: 403,
    });

    const run = yield* ScraperTest.run(Quotes, { maxPages: 3 }).pipe(
      Effect.provide(QuotesApiLive.pipe(Layer.provide(site.layer)))
    );

    expect(run.failure?._tag).toBe("Blocked");
    expect(run.items).toHaveLength(1);
  })
);

The Run fails with Blocked, and the quote from page 1 was still delivered. This is a Partial Run. On an instance the same thing happens: the result is failed and the items checked before the failure stay stored.

ScraperTest.run collects the items as they arrive, not from the Run's final value. A Run that fails has no final value, but it may already have delivered items.

Example (A changed body is SchemaDrift)

ts
it.effect("reports a changed body as SchemaDrift", () =>
  Effect.gen(function* drift() {
    const run = yield* ScraperTest.run(Quotes, { maxPages: 1 }).pipe(
      Effect.provide(
        QuotesApiLive.pipe(
          Layer.provide(FakeSite.layer({ [url(1)]: "<html>We moved</html>" }))
        )
      )
    );

    expect(run.failure?._tag).toBe("SchemaDrift");
    expect(run.items).toStrictEqual([]);
  })
);

FakeSite.layer is the fake without the record of requests, for a test that does not assert on them.

Example (Invalid input never reaches the site)

ts
it.effect("rejects invalid input before calling the site", () =>
  Effect.gen(function* invalidInput() {
    const site = yield* FakeSite.make({});

    const run = yield* ScraperTest.run(Quotes, { maxPages: 0 }).pipe(
      Effect.provide(QuotesApiLive.pipe(Layer.provide(site.layer)))
    );

    expect(run.failure?._tag).toBe("InvalidInput");
    expect(yield* site.requests).toStrictEqual([]);
  })
);

Run them:

sh
pnpm --filter @scwrap/quotes test
text
 Test Files  1 passed (1)
      Tests  4 passed (4)

Check that a test can fail ​

A test that cannot fail proves nothing. Before you trust a new test, plant a bug it should catch.

Change page < maxPages to page <= maxPages in src/api.ts and run the tests again:

text
 × follows has_next and stops at maxPages
      Tests  1 failed | 3 passed (4)

The test caught the extra page. Undo the change.

What to cover ​

BehaviourAn input that exposes a mistake
Correct mappingRecords that differ from each other, with empty and missing optional fields.
PaginationMore pages than the caller asked for, and a last page before the limit.
Declared failuresEach status the site can answer, a changed body, a transport error.
Early rejectionInvalid input, with an assertion that nothing was requested.
Empty is successA valid answer with no items completes without error.

Two things take these tests further:

  • Properties. it.effect.prop generates inputs from a schema instead of using one fixed example. The Earthquakes acceptance test generates whole feeds and every fault.
  • Retries. Download retries 5xx answers and transport errors with a delay. it.effect runs on a test clock, so such a test advances the clock with TestClock.adjust from effect/testing. The Earthquakes test shows how. FakeSite.unreachable as a reply is a transport error.

Testing a browser scraper ​

FakeSite fakes an HttpClient. A browser Implementation requires Browser instead, and what goes wrong in one, such as late rendering, waits and clicks that load nothing, only shows in a real browser. So its test keeps the browser real and fakes the network: nodeBrowser from @scwrap/browser/node launches a local Chromium with Playwright, and its prepare answers every request the page makes with Playwright's route. ScraperTest.run and the assertions stay the same.

The pages come from test/fixtures/. Record them from the real site once. For a page that renders with JavaScript, save it after it rendered: copy the <html> element in the browser's developer tools, or save Playwright's page.content(). Write small pages by hand in the test for what a recording cannot show, such as a page that never renders or a step limit.

Example (QuotesBrowserLive keeps the quotes of a recorded page when the next page is refused, in test/browser.test.ts)

ts
// @effect-diagnostics nodeBuiltinImport:off -- The test reads its fixture pages.
// @effect-diagnostics asyncFunction:off -- Fixture callbacks bridge Playwright's Promise API.
import { readFileSync } from "node:fs";

import { expect, it } from "@effect/vitest";
import { nodeBrowser } from "@scwrap/browser/node";
import { ScraperTest } from "@scwrap/domain/testing";
import { Effect, Layer } from "effect";

import { Quotes, QuotesBrowserLive, quotesOrigin } from "../src/index.js";

const fixture = (name: string) =>
  readFileSync(new URL(`fixtures/${name}`, import.meta.url), "utf-8");

const fixtureBrowser = (pages: Readonly<Record<string, string | number>>) =>
  nodeBrowser({
    prepare: async (context) => {
      await context.route("**/*", async (route) => {
        const page = pages[route.request().url()] ?? 404;

        await (typeof page === "number"
          ? route.fulfill({ body: `HTTP ${page}`, status: page })
          : route.fulfill({ body: page, contentType: "text/html" }));
      });
    },
  });

it.effect(
  "keeps rendered quotes when a later page is refused",
  () =>
    Effect.gen(function* partialRun() {
      const run = yield* ScraperTest.run(Quotes, { maxPages: 3 }).pipe(
        Effect.provide(
          QuotesBrowserLive.pipe(
            Layer.provide(
              fixtureBrowser({
                [`${quotesOrigin}/js/page/1/`]: fixture("page-1.html"),
                [`${quotesOrigin}/js/page/2/`]: 403,
              })
            )
          )
        )
      );

      expect(run.failure?._tag).toBe("Blocked");
      expect(run.items).toHaveLength(10);
      expect(run.items[0]?.author).toBe("Albert Einstein");
    }),
  60_000
);

page-1.html is https://quotes.toscrape.com/js/page/1/ saved after it rendered. A number is a status, sent with a body: Chromium reports an error status with an empty body as a failed navigation, and the Run would end with UpstreamDown instead of Blocked. The test needs @scwrap/browser, playwright and a Chromium, set up in Adding a browser.

A Scraper that opens pages in a country. nodeBrowser covers no location, so an Implementation that calls Browser.openIn({ location: "FR" }) does not compile with it. Build the test's provider with playwrightBrowser and name the country. The test answers every request itself, so no address is involved:

ts
const fixtureBrowserInFrance = (html: string) =>
  playwrightBrowser<"FR">({
    connect: async () => await chromium.launch(),
    prepare: (context) =>
      Effect.promise(async () => {
        await context.route("**/*", async (route) => {
          await route.fulfill({ body: html, contentType: "text/html" });
        });
      }),
  });

The real site. A test never calls it. To check an Implementation against it, run it from a script with nodeBrowser() and no prepare, which opens the live pages in your local Chromium (Run it in a local Chromium). Its requests leave from your own address. To see what a site answers an address in another country, run the script with browserUse and BROWSER_USE_API_KEY set, or deploy the Release and call it.

No paid browser sessions in tests. Every browserUse open starts a paid Browser Use session. Tests provide nodeBrowser or their own playwrightBrowser and never import @scwrap/browser/browser-use; only the Release chooses browserUse or browserRun. Outside an instance browserUse reads BROWSER_USE_API_KEY, so keep the key out of the environment your tests run in: without it, every open fails with BrowserError instead of starting a session.

For a unit test that needs no rendering, Browser.layer hands back a fake Page (Testing with a fake). Writing browser Implementations covers the stalls, cycles and step limits worth a test.

Next ​

The Scraper is proven. Deploying to a Worker puts it on an instance.