Convert Figma logo to code with AI

Netflix logopollyjs

Record, Replay, and Stub HTTP Interactions.

10,203
352
10,203
52

Top Related Projects

9,645

Test spies, stubs and mocks for JavaScript.

46,847

Fast, easy and reliable testing for anything that runs in a browser.

15,796

Seamless REST/GraphQL API mocking library for browser and Node.js.

12,708

HTTP server mocking and expectations library for Node.js

44,166

Delightful JavaScript Testing.

88,205

JavaScript API for Chrome and Firefox

Quick Overview

Polly.js is a powerful HTTP interaction recording and replaying library developed by Netflix. It allows developers to record, replay, and stub network requests, making it easier to write deterministic tests and simulate various network conditions.

Pros

  • Enhances test reliability by eliminating network dependencies
  • Supports multiple adapters (Fetch, XHR, Node HTTP)
  • Provides a flexible API for customizing recording and playback behavior
  • Integrates well with popular testing frameworks like Jest and Mocha

Cons

  • Learning curve for complex scenarios and configurations
  • May require additional setup for certain environments or frameworks
  • Limited support for WebSocket and other non-HTTP protocols
  • Potential for outdated recordings if not managed properly

Code Examples

Recording HTTP interactions:

import { Polly } from '@pollyjs/core';
import FetchAdapter from '@pollyjs/adapter-fetch';

Polly.register(FetchAdapter);

const polly = new Polly('MyRecording', {
  adapters: ['fetch']
});

// Your code that makes HTTP requests
await fetch('https://api.example.com/data');

await polly.stop();

Replaying recorded interactions:

import { Polly } from '@pollyjs/core';
import FetchAdapter from '@pollyjs/adapter-fetch';

Polly.register(FetchAdapter);

const polly = new Polly('MyRecording', {
  adapters: ['fetch'],
  mode: 'replay'
});

// Your code that makes HTTP requests
// Polly will intercept and replay the recorded responses
await fetch('https://api.example.com/data');

await polly.stop();

Stubbing network requests:

import { Polly } from '@pollyjs/core';
import FetchAdapter from '@pollyjs/adapter-fetch';

Polly.register(FetchAdapter);

const polly = new Polly('MyStub', {
  adapters: ['fetch']
});

polly.server.get('https://api.example.com/data').intercept((req, res) => {
  res.status(200).json({ message: 'Stubbed response' });
});

// Your code that makes HTTP requests
// Polly will return the stubbed response
await fetch('https://api.example.com/data');

await polly.stop();

Getting Started

  1. Install Polly.js and the desired adapter:

    npm install @pollyjs/core @pollyjs/adapter-fetch
    
  2. Set up Polly in your test file:

    import { Polly } from '@pollyjs/core';
    import FetchAdapter from '@pollyjs/adapter-fetch';
    
    Polly.register(FetchAdapter);
    
    const polly = new Polly('MyFirstRecording', {
      adapters: ['fetch'],
      recordIfMissing: true
    });
    
    // Your test code here
    
    await polly.stop();
    
  3. Run your tests. Polly will record HTTP interactions on the first run and replay them in subsequent runs.

Competitor Comparisons

9,645

Test spies, stubs and mocks for JavaScript.

Pros of Sinon

  • More mature and widely adopted project with a larger community
  • Broader scope, offering mocks, stubs, and spies for various testing scenarios
  • Extensive documentation and examples available

Cons of Sinon

  • Steeper learning curve due to its extensive feature set
  • May be overkill for projects that only need HTTP mocking

Code Comparison

Sinon (mocking an HTTP request):

const xhr = sinon.useFakeXMLHttpRequest();
const requests = [];
xhr.onCreate = (req) => requests.push(req);

// Make a request
const request = new XMLHttpRequest();
request.open('GET', '/users');
request.send();

// Respond to the request
requests[0].respond(200, { 'Content-Type': 'application/json' }, '{"id": 1}');

PollyJS (recording and replaying an HTTP request):

const polly = new Polly('My Recording');
const { server } = polly;

server.get('/users').intercept((req, res) => {
  res.status(200).json({ id: 1 });
});

await fetch('/users');
await polly.stop();

Both Sinon and PollyJS offer HTTP mocking capabilities, but PollyJS focuses specifically on recording and replaying HTTP interactions, while Sinon provides a broader set of mocking tools for various testing scenarios. PollyJS may be easier to use for HTTP-specific mocking, while Sinon offers more flexibility for complex testing requirements.

46,847

Fast, easy and reliable testing for anything that runs in a browser.

Pros of Cypress

  • More comprehensive end-to-end testing framework with built-in assertion library and command chaining
  • Real-time reloading and time travel debugging for easier test development
  • Extensive documentation and large community support

Cons of Cypress

  • Limited to testing web applications in Chrome-based browsers
  • Can be slower for large test suites due to its real browser approach
  • Steeper learning curve for developers new to end-to-end testing

Code Comparison

PollyJS (Recording an API interaction):

await polly.record();
await fetch('https://api.example.com/data');
await polly.stop();

Cypress (Testing an API interaction):

cy.request('https://api.example.com/data')
  .its('status')
  .should('eq', 200);

Key Differences

  • PollyJS focuses on recording and replaying HTTP interactions, while Cypress is a full-featured testing framework
  • PollyJS can be used with various testing frameworks, whereas Cypress is a standalone solution
  • PollyJS is more flexible for different types of applications, while Cypress specializes in web application testing

Use Cases

  • Choose PollyJS for lightweight HTTP interaction recording and stubbing across different environments
  • Opt for Cypress when building comprehensive end-to-end tests for web applications with a focus on developer experience
15,796

Seamless REST/GraphQL API mocking library for browser and Node.js.

Pros of MSW

  • Supports both browser and Node.js environments, offering greater flexibility
  • Uses Service Workers for browser interception, providing a more realistic mocking experience
  • Easier setup and configuration, with a more intuitive API

Cons of MSW

  • Relatively newer project with a smaller community compared to Pollyjs
  • Limited built-in integrations with testing frameworks

Code Comparison

MSW:

import { rest } from 'msw'
import { setupServer } from 'msw/node'

const server = setupServer(
  rest.get('/api/user', (req, res, ctx) => {
    return res(ctx.json({ name: 'John Doe' }))
  })
)

Pollyjs:

import { Polly } from '@pollyjs/core'
import NodeHttpAdapter from '@pollyjs/adapter-node-http'
import FSPersister from '@pollyjs/persister-fs'

Polly.register(NodeHttpAdapter)
Polly.register(FSPersister)

const polly = new Polly('MyRecording', {
  adapters: ['node-http'],
  persister: 'fs'
})

Both MSW and Pollyjs are powerful tools for mocking HTTP requests in JavaScript applications. MSW offers a more modern approach with Service Worker integration and an easier setup process. Pollyjs, developed by Netflix, provides robust recording and playback capabilities, making it particularly useful for larger, more complex applications. The choice between the two depends on specific project requirements and preferences.

12,708

HTTP server mocking and expectations library for Node.js

Pros of nock

  • Simpler setup and usage, requiring less configuration
  • Wider adoption and longer history in the Node.js ecosystem
  • Supports more HTTP libraries out of the box

Cons of nock

  • Limited browser support compared to Pollyjs
  • Lacks advanced features like automatic request recording and playback
  • No built-in persistence layer for recorded interactions

Code Comparison

nock:

const nock = require('nock');

nock('https://api.example.com')
  .get('/users')
  .reply(200, { users: ['Alice', 'Bob'] });

Pollyjs:

import { Polly } from '@pollyjs/core';
import XHRAdapter from '@pollyjs/adapter-xhr';

const polly = new Polly('MyRecording', {
  adapters: [XHRAdapter]
});

polly.server.get('https://api.example.com/users').intercept((req, res) => {
  res.status(200).json({ users: ['Alice', 'Bob'] });
});

Both nock and Pollyjs are popular HTTP mocking libraries, but they have different strengths. nock is simpler to set up and use, making it a good choice for quick mocking in Node.js environments. It has broader support for various HTTP libraries out of the box.

Pollyjs, on the other hand, offers more advanced features like automatic request recording and playback, which can be particularly useful for complex testing scenarios. It also provides better browser support and a built-in persistence layer for recorded interactions.

The code comparison shows that nock has a more concise syntax for basic mocking, while Pollyjs requires more setup but offers more flexibility in handling requests and responses.

44,166

Delightful JavaScript Testing.

Pros of Jest

  • More comprehensive testing framework with built-in assertion library, mocking, and code coverage
  • Larger community and ecosystem, with extensive documentation and third-party extensions
  • Zero-config setup for most JavaScript projects, making it easier to get started

Cons of Jest

  • Heavier and slower for large projects compared to lightweight alternatives
  • Less focused on HTTP mocking and recording, which is PollyJS's primary purpose
  • May require additional setup for certain types of frontend testing scenarios

Code Comparison

Jest example:

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

PollyJS example:

await polly.record();
const response = await fetch('https://api.example.com/data');
const data = await response.json();
expect(data).toEqual({ success: true });

PollyJS is specifically designed for recording and replaying HTTP interactions, making it ideal for API testing and mocking. Jest, on the other hand, is a more general-purpose testing framework that can handle various types of tests but may require additional setup for advanced HTTP mocking scenarios.

While Jest provides a comprehensive solution for most JavaScript testing needs, PollyJS offers a specialized approach to HTTP interaction testing, which can be particularly useful for projects heavily reliant on external APIs or complex network requests.

88,205

JavaScript API for Chrome and Firefox

Pros of Puppeteer

  • More comprehensive browser automation capabilities
  • Supports headless Chrome and Firefox
  • Larger community and ecosystem

Cons of Puppeteer

  • Heavier resource usage
  • Steeper learning curve for simple tasks
  • Not specifically designed for recording and replaying HTTP interactions

Code Comparison

PollyJS example:

await Polly.record('My Recording', async () => {
  await page.goto('https://example.com');
  await page.click('#submit-button');
});

Puppeteer example:

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.click('#submit-button');
await browser.close();

PollyJS focuses on recording and replaying HTTP interactions, making it ideal for API testing and mocking. It's lightweight and easy to set up for specific use cases.

Puppeteer offers more extensive browser automation features, making it suitable for a wider range of tasks like web scraping, generating PDFs, and running UI tests. However, it requires more setup and resources.

PollyJS is better for projects primarily concerned with API testing and mocking, while Puppeteer excels in scenarios requiring full browser control and automation.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Polly.JS

Record, Replay, and Stub HTTP Interactions

Build Status license

Polly.JS is a standalone, framework-agnostic JavaScript library that enables recording, replaying, and stubbing of HTTP interactions. By tapping into multiple request APIs across both Node & the browser, Polly.JS is able to mock requests and responses with little to no configuration while giving you the ability to take full control of each request with a simple, powerful, and intuitive API.

Interested in contributing or just seeing Polly in action? Head over to CONTRIBUTING.md to learn how to spin up the project!

Why Polly?

Keeping fixtures and factories in parity with your APIs can be a time consuming process. Polly alleviates this process by recording and maintaining actual server responses while also staying flexible.

  • Record your test suite's HTTP interactions and replay them during future test runs for fast, deterministic, accurate tests.
  • Use Polly's client-side server to modify or intercept requests and responses to simulate different application states (e.g. loading, error, etc.).

Features

  • 🚀 Node & Browser Support
  • ⚡️️ Simple, Powerful, & Intuitive API
  • 💎 First Class Mocha & QUnit Test Helpers
  • 🔥 Intercept, Pass-Through, and Attach Events
  • 📼 Record to Disk or Local Storage
  • ⏱ Slow Down or Speed Up Time

Getting Started

Check out the Quick Start documentation to get started.

Usage

Let's take a look at what an example test case would look like using Polly.

import { Polly } from '@pollyjs/core';
import XHRAdapter from '@pollyjs/adapter-xhr';
import FetchAdapter from '@pollyjs/adapter-fetch';
import RESTPersister from '@pollyjs/persister-rest';

/*
  Register the adapters and persisters we want to use. This way all future
  polly instances can access them by name.
*/
Polly.register(XHRAdapter);
Polly.register(FetchAdapter);
Polly.register(RESTPersister);

describe('Netflix Homepage', function () {
  it('should be able to sign in', async function () {
    /*
      Create a new polly instance.

      Connect Polly to both fetch and XHR browser APIs. By default, it will
      record any requests that it hasn't yet seen while replaying ones it
      has already recorded.
    */
    const polly = new Polly('Sign In', {
      adapters: ['xhr', 'fetch'],
      persister: 'rest'
    });
    const { server } = polly;

    /* Intercept all Google Analytic requests and respond with a 200 */
    server
      .get('/google-analytics/*path')
      .intercept((req, res) => res.sendStatus(200));

    /* Pass-through all GET requests to /coverage */
    server.get('/coverage').passthrough();

    /* start: pseudo test code */
    await visit('/login');
    await fillIn('email', 'polly@netflix.com');
    await fillIn('password', '@pollyjs');
    await submit();
    /* end: pseudo test code */

    expect(location.pathname).to.equal('/browse');

    /*
      Calling `stop` will persist requests as well as disconnect from any
      connected browser APIs (e.g. fetch or XHR).
    */
    await polly.stop();
  });
});

The above test case would generate the following HAR file which Polly will use to replay the sign-in response when the test is rerun:

{
  "log": {
    "_recordingName": "Sign In",
    "browser": {
      "name": "Chrome",
      "version": "67.0"
    },
    "creator": {
      "name": "Polly.JS",
      "version": "0.5.0",
      "comment": "persister:rest"
    },
    "entries": [
      {
        "_id": "06f06e6d125cbb80896c41786f9a696a",
        "_order": 0,
        "cache": {},
        "request": {
          "bodySize": 51,
          "cookies": [],
          "headers": [
            {
              "name": "content-type",
              "value": "application/json; charset=utf-8"
            }
          ],
          "headersSize": 97,
          "httpVersion": "HTTP/1.1",
          "method": "POST",
          "postData": {
            "mimeType": "application/json; charset=utf-8",
            "text": "{\"email\":\"polly@netflix.com\",\"password\":\"@pollyjs\"}"
          },
          "queryString": [],
          "url": "https://netflix.com/api/v1/login"
        },
        "response": {
          "bodySize": 0,
          "content": {
            "mimeType": "text/plain; charset=utf-8",
            "size": 0
          },
          "cookies": [],
          "headers": [],
          "headersSize": 0,
          "httpVersion": "HTTP/1.1",
          "redirectURL": "",
          "status": 200,
          "statusText": "OK"
        },
        "startedDateTime": "2018-06-29T17:31:55.348Z",
        "time": 11,
        "timings": {
          "blocked": -1,
          "connect": -1,
          "dns": -1,
          "receive": 0,
          "send": 0,
          "ssl": -1,
          "wait": 11
        }
      }
    ],
    "pages": [],
    "version": "1.2"
  }
}

Prior Art

The "Client Server" API of Polly is heavily influenced by the very popular mock server library pretender. Pretender supports XHR and Fetch stubbing and is a great lightweight alternative to Polly if your project does not require persisting capabilities or Node adapters.

Thank you to all contributors especially the maintainers: trek, stefanpenner, and xg-wang.

Contributors

License

Copyright (c) 2018 Netflix, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

NPM DownloadsLast 30 Days