pollyjs README

The project's README from github.com/Netflix/pollyjs. As one markdown file: README.md.

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.

Features

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', '[email protected]');
    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\":\"[email protected]\",\"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.

pollyjs (Netflix/pollyjs)

Searching Database…

10.3K ·GitHub
这是做什么的?这是 Polly.JS,Netflix 出品的一个 JavaScript 库,可以录制、回放和模拟(stub)HTTP 交互,这样你的测试套件就不用连着一个真实的 API 也能跑。
它是加到我测试里的库,还是我得单独跑一个 mock 服务器?是一个接入你测试的库,不是单独的服务器。它会挂接你的代码在 Node 和浏览器里已经在用的请求 API,几乎不用任何配置就能模拟响应。
我怎么把它接入我的测试套件?从 npm 安装 @pollyjs 的包,并在你的测试初始化代码里注册它的辅助工具,具体可以照着 README 链接的快速入门文档来做。
它开箱即用支持哪些测试框架?它为 Mocha 和 QUnit 提供了一流的辅助工具,其他场景下则不绑定任何框架——不需要额外的运行时或后端。
它也能用于浏览器测试吗,还是只能在 Node 里用?都可以——Node 和浏览器支持是它列出的第一个特性,同一套录制/回放配置既能覆盖服务端测试,也能覆盖浏览器内测试。
我能在商业项目里用它吗?可以——它采用 Apache-2.0 许可证(版权归 Netflix, Inc. 所有),这是一种宽松的许可证,商业使用没有任何附加条件。
录制和回放的流程到底是怎么运作的?第一次运行时,Polly 会把你测试套件真实的 HTTP 交互录制成一个 HAR 文件;之后每次重跑都会回放这份录制,而不是真的去请求服务器,从而得到快速、稳定、准确的测试。
录制的内容存在哪里?在 Node 里会写到磁盘上;在浏览器里则存到 Local Storage。无论哪种方式,Polly 下次运行时都会读取它们。
我能不能不重新录制就模拟出错或加载中的状态?可以——客户端服务器(client-side server)让你能拦截并修改请求和响应,来模拟加载中或出错之类的状态,你甚至可以调快或调慢时间来测试延迟相关的行为。
它和 mock 服务器 Pretender 有什么区别?Polly 的 Client Server API 在很大程度上受到了 Pretender 的启发,README 里说,如果你不需要持久化录制或 Node 适配器,Pretender 是一个很棒的轻量替代方案。
What are similar projects?msw, Mock, nock, react-testing-library, jsdom, testify, mockito, jest
Creator
Netflix
Size
3.6 MB
Stars
10.3K
Updated
CommitMay 31
Age
8y
Commits · 90 Days