vitalets / playwright-network-cache

Cache and mock network requests in Playwright
MIT License
27 stars 2 forks source link

Usage outside of test files? #2

Closed bennom closed 1 month ago

bennom commented 1 month ago

Hey, just stumbled over that project here. It's a very interesting approach and I'm currently investigating if it might help me with a little pet project. But my use case is not actual testing with Playwright, but more like a headless app for my own educational purposes.

(fictional) scenario: image, I have a super simple app that goes to a website, clicks a button and that's it:

import { CacheRoute } from 'playwright-network-cache';

const appRunner = async (url) => {
  const page = await context.newPage();

  page.on('request', async request => {
    await new CacheRoute(page).GET(request.url(), {
      ttlMinutes: 60,
      match: req => {
        const requestUrl = new URL(req.url()).href;
        return myFunctionToCheckWeatherToCacheOrNot(requestUrl);
      },
    });
  });

  // do something
  await page.goto(url)
  await page.locator(someButtonId).click()
}

// some random initiator
appRunner('https://example.com')
appRunner('https://example.com') // 2nd run uses cached files?

I can see that on my file system, there's a .network-cache directory containing the files I want to cache. How can I validate, that those cached files are used for the second run of appRunner()?

Thanks in advance and thank you for the efforts you put in this project :)

vitalets commented 1 month ago

Hi @bennom

You can run code with env var DEBUG=playwright-network-cache to see cached / real requests. Example output: image

bennom commented 1 month ago

Ah, that's nice. Somehow I missed that. Thank you :)