npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

puppeteer-request-intercepter

v3.0.1

Published

Intercept API Requests and return Mocked Data

Downloads

369

Readme

puppeteer-request-intercepter

Intercept API Requests and return Mocked Data

Install

$ npm install puppeteer-request-intercepter

Usage


const puppeteer = require('puppeteer');

const { initFixtureRouter } = require('puppeteer-request-intercepter');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  const fixtureRouter = await initFixtureRouter(page, { baseUrl: 'https://news.ycombinator.com' });
  fixtureRouter.route('GET', '/y18.gif', 'y18.gif', { contentType: 'image/gif' });

  await page.goto('https://news.ycombinator.com', { waitUntil: 'networkidle2' });
  await page.pdf({ path: 'hn.pdf', format: 'A4' });

  await browser.close();
})();

API

initFixtureRouter(page, options?)

Initialize a new FixtureRouter class.

This class is responsible for configuring and handling Puppeteer requests. Eg. page.on('request') and page.on('response')

Returns a FixtureRouter object with route and routeFixture functions.

page

Type: object

An instance of the Puppeteer page object.

options

Type: object Default: {}

Decode the keys and values. URL components are decoded with decode-uri-component.

baseUrl

Type: string Default: ''

Base Url for relative fixture routes (ex. /api/v1/users).

const fixtureRouter = await initFixtureRouter(page, { baseUrl: 'https://news.ycombinator.com' });
fixtureBasePath

Type: string Default: ./puppeteer/fixtures

Base path where the fixture files are located (and will be created if they don't exist).

fixtureRouter.route(method, route, fixturePath, options)

Add a FixtureRoute to the FixtureRouter instance.

method

Type: string

The HttpMethod to match:

  • GET
  • POST
  • PATCH
  • PUT
  • DELETE
  • OPTIONS

route

Type: string

The full or relative Url to match.

Comparison is done using startsWith() and the order in which FixtureRoute's are added matters. The first one found will be used.

Put the most specific match first. Ex:

fixtureRouter.route('GET', '/api/v1/users/bill', 'bill.json');
fixtureRouter.route('GET', '/api/v1/users', 'all-users.json');

fixturePath

Type: string

Relative path of the fixture file to use (or create).

options

Type: object Default: {}

FixtureRouteOptions to use for the response.

contentType

Type: string Default: application/json

Specifies the Content-Type response header.

status

Type: number

Specifies the response status code.

fixtureRouter.routeFixture(fixtureRoute)

Add a FixtureRoute to the FixtureRouter instance.

Options are the same as fixtureRouter.route() except it accepts an object of parameters instead of individual ones.

fixtureRouter.findRoute(method, url)

Returns the first FixtureRoute that matches the provided method and url. If there are no matches it returns undefined.

method

Type: string

The HttpMethod to match.

url

Type: string

The full or relative Url to match.

If it's a relative Url, the configured baseUrl will be used.

createFixture(method, route, fixturePath, options)

Convenience method for creating FixtureRoute's.

Same API as fixtureRouter.route.

Useful when using BackstopJS with a custom scenarios.fixtures array.

BackstopJS Example

onBefore.ts:
import { Scenario } from 'backstopjs';
import { Page } from 'puppeteer';
import { initFixtureRouter } from 'puppeteer-request-intercepter';

// tslint:disable-next-line: export-name
export = async (page: Page, scenario: Scenario, vp) => {
  // Configure fixtures:
  if (scenario.fixtures) {
    const fixtureRouter = await initFixtureRouter(page, {
      baseUrl: `http://localhost:8080`,
      fixtureBasePath: 'backstop_data/engine_scripts/fixtures',
    });

    scenario.fixtures.forEach((fixture) => {
      fixtureRouter.routeFixture(fixture);
    });
  }
};
backstopConfig.ts:

import { Config, Scenario } from 'backstopjs';
import { Page } from 'puppeteer';
import { createFixture, FixtureRoute } from 'puppeteer-request-intercepter';

const globalFixtures: FixtureRoute[] = [
  createFixture('GET', '/api/v1/alerts', 'alerts.json'),
];

const config: Config = {
  id: 'MyProject',
  viewports: [
    {
      label: 'phone',
      width: 320,
      height: 1200,
    },
    {
      label: 'tablet',
      width: 1024,
      height: 768,
    },
    {
      label: 'desktop',
      width: 1200,
      height: 900,
    },
  ],
  paths: {
    bitmaps_reference: 'backstop_data/bitmaps_reference',
    bitmaps_test: 'backstop_data/bitmaps_test',
    engine_scripts: 'backstop_data/dist/engine_scripts',
    html_report: 'backstop_data/html_report',
    ci_report: 'backstop_data/ci_report',
  },
  report: ['browser'],
  engine: 'puppeteer',
  engineOptions: {
    args: ['--no-sandbox'],
  },
  asyncCaptureLimit: 5,
  asyncCompareLimit: 50,
  debug: false,
  debugWindow: false,
  onBeforeScript: 'onBefore.js',
  onReadyScript: 'onReady.js',
  scenarios: [
    {
      label: 'dashboards',
      url: url('/dashboards'),
      fixtures: [
        ...globalFixtures,
        createFixture('GET', '/api/v1/dashboards', 'dashboards.json')
      ],
    },
  ],
};

export = config;