MockRequest

# MockRequest

Extends Helper

This helper allows to mock requests while running tests in Puppeteer or WebDriver. For instance, you can block calls to 3rd-party services like Google Analytics, CDNs. Another way of using is to emulate requests from server by passing prepared data.

# Installations

Requires Polly.js library by Netflix installed

npm i @pollyjs/core @pollyjs/adapter-puppeteer --save-dev

Requires Puppeteer helper or WebDriver helper enabled

# Configuration

Just enable helper in config file:

helpers: {
   Puppeteer: {
     // regular Puppeteer config here
   },
   MockRequest: {}
}

Partially works with WebDriver helper

Polly config options can be passed as well:

// enable replay mode
helpers: {
 Puppeteer: {
   // regular Puppeteer config here
 },
 MockRequest: {
    mode: 'replay',
 },
}

# Usage

Use I.mockRequest to intercept and mock requests.

# Parameters

  • config

# _checkAndStartMocking

Starts mocking if it's not started yet.

# _connectPuppeteer

Creates a polly instance by registering puppeteer adapter with the instance

# Parameters

  • title any

# _connectWebDriver

Creates polly object in the browser window context using xhr and fetch adapters, after loading PollyJs and adapter scripts.

# Parameters

  • title any

# mockRequest

Mock response status

I.mockRequest('GET', '/api/users', 200);
I.mockRequest('ANY', '/secretsRoutes/*', 403);
I.mockRequest('POST', '/secrets', { secrets: 'fakeSecrets' });
I.mockRequest('GET', '/api/users/1', 404, 'User not found');

Multiple requests

I.mockRequest('GET', ['/secrets', '/v2/secrets'], 403);

# Parameters

  • method string request method. Can be GET, POST, PUT, etc or ANY.
  • oneOrMoreUrls (string | Array<string>) url(s) to mock. Can be exact URL, a pattern, or an array of URLs.
  • dataOrStatusCode (number | string | object) status code when number provided. A response body otherwise
  • additionalData (string | object) response body when a status code is set by previous parameter.

# startMocking

Starts mocking of http requests. Used by mockRequest method to automatically start mocking requests.

# Parameters

  • title any

# stopMocking

Stops mocking requests.

Last Updated: 1/10/2020, 7:48:42 PM