Configuration

November 30, 2021 · View on GitHub

A Polly instance can be configured by passing a configuration object to the constructor's 2nd argument:

new Polly('<Recording Name>', {
  recordIfMissing: false
});

Or via the configure method on the instance:

const polly = new Polly('<Recording Name>');

polly.configure({
  recordIfMissing: false
});

Defaults

config.js

logLevel

Type: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'silent' Default: 'warn'

Set the log level for the polly instance.

Example

polly.configure({
  logLevel: 'info'
});

recordIfMissing

Type: Boolean Default: true

If a request's recording is not found, pass-through to the server and record the response.

Example

polly.configure({
  recordIfMissing: true
});

recordFailedRequests

Type: Boolean Default: false

If false, Polly will throw when attempting to persist any failed requests. A request is considered to be a failed request when its response's status code is ≥ 400.

Example

polly.configure({
  recordFailedRequests: true
});

flushRequestsOnStop

Type: Boolean Default: false

Await any unresolved requests handled by the polly instance (via flush) when stop is called.

Example

polly.configure({
  flushRequestsOnStop: true
});

expiresIn

Type: String Default: null

After how long the recorded request will be considered expired from the time it was persisted. A recorded request is considered expired if the recording's startedDateTime plus the current expiresIn duration is in the past.

Example

polly.configure({
  expiresIn: '30d5h10m' // expires in 30 days, 5 hours, and 10 minutes
});

polly.configure({
  expiresIn: '5 min 10 seconds 100 milliseconds' // expires in 5 minutes, 10 seconds, and 100 milliseconds
});

expiryStrategy

Type: 'warn' | 'error' | 'record' Default: 'warn'

The strategy for what should occur when Polly tries to use an expired recording in replay mode. Can be one of the following:

  • warn: Log a console warning about the expired recording.
  • error: Throw an error.
  • record: Re-record by making a new network request.

Example

polly.configure({
  expiryStrategy: 'error'
});

mode

Type: String Default: 'replay'

The Polly mode. Can be one of the following:

  • replay: Replay responses from recordings.
  • record: Force Polly to record all requests. This will overwrite recordings that already exist.
  • passthrough: Passes all requests through directly to the server without recording or replaying.

Example

polly.configure({
  mode: 'record'
});

adapters

Type: Array[String|Function] Default: []

The adapter(s) polly will hook into.

Example

import XHRAdapter from '@pollyjs/adapter-xhr';
import FetchAdapter from '@pollyjs/adapter-fetch';

// Register the xhr adapter so its accessible by all future polly instances
Polly.register(XHRAdapter);

polly.configure({
  adapters: ['xhr', FetchAdapter]
});

adapterOptions

Type: Object Default: {}

Options to be passed into the adapters keyed by the adapter name.

?> NOTE: Check out the appropriate documentation pages for each adapter for more details.

Example

polly.configure({
  adapterOptions: {
    fetch: {
      context: win
    }
  }
});

persister

Type: String|Function Default: null

The persister to use for recording and replaying requests.

Example

import RESTPersister from '@pollyjs/persister-rest';
import LocalStoragePersister from '@pollyjs/persister-local-storage';

// Register the local-storage persister so its accessible by all future polly instances
Polly.register(LocalStoragePersister);

polly.configure({
  persister: 'local-storage'
});

polly.configure({
  persister: RESTPersister
});

persisterOptions

Type: Object Default: {}

Options to be passed into the persister keyed by the persister name.

?> NOTE: Check out the appropriate documentation pages for each persister for more details.

Example

polly.configure({
  persisterOptions: {
    rest: {
      apiNamespace: '/polly'
    }
  }
});

keepUnusedRequests

Type: Boolean Default: false

When disabled, requests that have not been captured by the running Polly instance will be removed from any previous recording. This ensures that a recording will only contain the requests that were made during the lifespan of the Polly instance. When enabled, new requests will be appended to the recording file.

Example

polly.configure({
  persisterOptions: {
    keepUnusedRequests: true
  }
});

disableSortingHarEntries

Type: Boolean Default: false

When disabled, entries in the the final HAR will be sorted by the request's timestamp. This is done by default to satisfy the HAR 1.2 spec but can be enabled to improve diff readability when committing recordings to git.

Example

polly.configure({
  persisterOptions: {
    disableSortingHarEntries: true
  }
});

timing

Type: Function Default: Timing.fixed(0)

The timeout delay strategy used when replaying requests.

Example

import { Timing } from '@pollyjs/core';

polly.configure({
  // Replay requests at 300% the original speed to simulate a 3g connection
  timing: Timing.relative(3.0)
});

polly.configure({
  // Replay requests with a 200ms delay
  timing: Timing.fixed(200)
});

matchRequestsBy

Type: Object

Default:

matchRequestsBy: {
  method: true,
  headers: true,
  body: true,
  order: true,

  url: {
    protocol: true,
    username: true,
    password: true,
    hostname: true,
    port: true,
    pathname: true,
    query: true,
    hash: false
  }
}

Request matching configuration. Each of these options are used to generate a GUID for the request.

  • method

    Type: Boolean | Function Default: true

    The request method (e.g. GET, POST)

    Example

    polly.configure({
      matchRequestsBy: {
        method: false
      }
    });
    
    polly.configure({
      matchRequestsBy: {
        method(method, req) {
          return method.toLowerCase();
        }
      }
    });
    
  • headers

    Type: Boolean | Function | Object Default: true

    The request headers.

    Example

    polly.configure({
      matchRequestsBy: {
        headers: false
      }
    });
    
    polly.configure({
      matchRequestsBy: {
        headers(headers, req) {
          delete headers['X-AUTH-TOKEN'];
          return headers;
        }
      }
    });
    

    Specific headers can also be excluded with the following:

    Example

    polly.configure({
      matchRequestsBy: {
        headers: {
          exclude: ['X-AUTH-TOKEN']
        }
      }
    });
    
  • body

    Type: Boolean | Function Default: true

    The request body.

    !> Please make sure you do not modify the passed in body. If you need to make changes, create a copy of it first. The body function receives the actual request body — any modifications to it will result with it being sent out with the request.

    Example

    polly.configure({
      matchRequestsBy: {
        body: false
      }
    });
    
    polly.configure({
      matchRequestsBy: {
        body(body, req) {
          const json = JSON.parse(body);
    
          delete json.email;
          return JSON.stringify(json);
        }
      }
    });
    
  • order

    Type: Boolean Default: true

    The order the request came in. Take the following scenario:

    // Retrieve our model
    let model = await fetch('/models/1').then((res) => res.json());
    
    // Modify the model
    model.foo = 'bar';
    
    // Save the model with our new change
    await fetch('/models/1', { method: 'POST', body: JSON.stringify(model) });
    
    // Get our updated model
    model = await fetch('/models/1').then((res) => res.json());
    
    // Assert that our change persisted
    expect(model.foo).to.equal('bar');
    

    The order of the requests matter since the payload for the first and last fetch are different.

    Example

    polly.configure({
      matchRequestsBy: {
        order: false
      }
    });
    
  • url

    Type: Boolean | Function | Object Default: { protocol: true, username: true, ... }

    The request url.

    Example

    polly.configure({
      matchRequestsBy: {
        url: false
      }
    });
    
    polly.configure({
      matchRequestsBy: {
        url(url, req) {
          return url.replace('test', '');
        }
      }
    });
    
    polly.configure({
      matchRequestsBy: {
        url: {
          protocol(protocol) {
            return 'https:';
          },
          query: false
        }
      }
    });
    
  • url.protocol

    Type: Boolean | Function Default: true

    The request url protocol (e.g. http:).

    Example

    polly.configure({
      matchRequestsBy: {
        url: {
          protocol: false
        }
      }
    });
    
    polly.configure({
      matchRequestsBy: {
        url: {
          protocol(protocol, req) {
            return 'https:';
          }
        }
      }
    });
    
  • url.username

    Type: Boolean | Function Default: true

    Username of basic authentication.

    Example

    polly.configure({
      matchRequestsBy: {
        url: {
          username: false
        }
      }
    });
    polly.configure({
      matchRequestsBy: {
        url: {
          username(username, req) {
            return 'username';
          }
        }
      }
    });
    
  • url.password

    Type: Boolean | Function Default: true

    Password of basic authentication.

    Example

    polly.configure({
      matchRequestsBy: {
        url: {
          password: false
        }
      }
      matchRequestsBy: {
        url: {
          password(password, req) {
            return 'password';
          }
        }
      }
    });
    
  • url.hostname

    Type: Boolean | Function Default: true

    Host name without port number.

    Example

    polly.configure({
      matchRequestsBy: {
        url: {
          hostname: false
        }
      }
    });
    
    polly.configure({
      matchRequestsBy: {
        url: {
          hostname(hostname, req) {
            return hostname.replace('.com', '.net');
          }
        }
      }
    });
    
  • url.port

    Type: Boolean | Function Default: true

    Port number.

    Example

    polly.configure({
      matchRequestsBy: {
        url: {
          port: false
        }
      }
    });
    
    polly.configure({
      matchRequestsBy: {
        url: {
          port(port, req) {
            return 3000;
          }
        }
      }
    });
    
  • url.pathname

    Type: Boolean | Function Default: true

    URL path.

    Example

    polly.configure({
      matchRequestsBy: {
        url: {
          pathname(pathname, req) {
            return pathname.replace('/api/v1', '/api');
          }
        }
      }
    });
    
  • url.query

    Type: Boolean | Function Default: true

    Sorted query string.

    Example

    polly.configure({
      matchRequestsBy: {
        url: {
          query: false
        }
      }
    });
    
    polly.configure({
      matchRequestsBy: {
        url: {
          query(query, req) {
            return { ...query, token: '' };
          }
        }
      }
    });
    
  • url.hash

    Type: Boolean | Function Default: false

    The "fragment" portion of the URL including the pound-sign (#).

    Example

    polly.configure({
      matchRequestsBy: {
        url: {
          hash: true
        }
      }
    });
    
    polly.configure({
      matchRequestsBy: {
        url: {
          hash(hash, req) {
            return hash.replace(/token=[0-9]+/, '');
          }
        }
      }
    });