@codeceptjs/mock-request

中文文档
0.3.1发布于 2021/11/10ISCCommonJS近 30 天下载 1万

Mocking requests with PollyJS for CodeceptJS

原始使用文档
文档目录3 节
  1. API
  2. MockRequest
  3. Usage

MockRequest helper for CodeceptJS

Build Status

Playwright engine is not supported by this helper. Use native Playwright API to mock requests.

👻 Implements HTTP request mocking, record & replay via PollyJS for CodeceptJS.

Use it to:

  • 📼 Record & Replay HTTP requests
  • 📲 Replace server responses
  • ⛔ Block third party integrations: analytics, chats, support systems.

Works with Puppeteer & WebDriver helpers of CodeceptJS.

API

Table of Contents

MockRequest

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.

MockRequest helper works in these modes:

  • passthrough (default) - mock prefefined HTTP requests
  • record - record all requests into a file
  • replay - replay all recorded requests from a file

Combining record/replay modes allows testing websites with large datasets.

To use in passthrough mode set rules to mock requests and they will be automatically intercepted and replaced:

// default mode
I.mockRequest('GET', '/api/users', '[]');

In record-replay mode start mocking to make HTTP requests recorded/replayed, and stop when you don't need to block requests anymore:

// record or replay all XHR for /users page
I.startMocking();
I.amOnPage('/users');
I.stopMocking();

Installations

npm i @codeceptjs/mock-request --save-dev

Requires Puppeteer helper or WebDriver helper enabled

Configuration

With Puppeteer

Enable helper in config file:

helpers: {
   Puppeteer: {
     // regular Puppeteer config here
   },
   MockRequestHelper: {
     require: '@codeceptjs/mock-request',
   }
}

Polly config options can be passed as well:

// sample options
helpers: {
  MockRequestHelper: {
     require: '@codeceptjs/mock-request',
     mode: record,
     recordIfMissing: true,
     recordFailedRequests: false,
     expiresIn: null,
     persisterOptions: {
       keepUnusedRequests: false
       fs: {
         recordingsDir: './data/requests',
       },
    },
  }
}

TROUBLESHOOTING: Puppeteer does not mock requests in headless mode:

Problem: request mocking does not work and in debug mode you see this in output:

Access to fetch at {url} from origin {url} has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Solution: update Puppeteer config to include --disable-web-security arguments:

 Puppeteer: {
   show: false,
   chrome: {
     args: [
       '--disable-web-security',
     ],
   },
 },

With WebDriver

This helper partially works with WebDriver. It can intercept and mock requests only on already loaded page.

helpers: {
   WebDriver: {
     // regular WebDriver config here
   },
   MockRequestHelper: {
     require: '@codeceptjs/mock-request',
   }
}

Record/Replay mode is not tested in WebDriver but technically can work with REST Persister

Usage

👻 Mock Requests

To intercept API requests and mock them use following API

Calling mockRequest or mockServer will start mocking, if it was not enabled yet.

I.startMocking(); // optionally
I.mockRequest('/google-analytics/*path', 200);
// return an empty successful response 
I.mockRequest('GET', '/api/users', 200);
// mock users api
I.mockServer(server => {
  server.get('https://server.com/api/users*').
    intercept((req, res) => { res.status(200).json(users);
  });
});
I.click('Get users);
I.stopMocking();

📼 Record & Replay

At this moment works only with Puppeteer

Record & Replay mode allows you to record all xhr & fetch requests and save them to file. On next runs those requests can be replayed. By default, it stores all passed requests, but this behavior can be customized with I.mockServer

Set mode via enironment variable, replay mode by default:

// enable replay mode
helpers: {
 Puppeteer: {
   // regular Puppeteer config here
 },
 MockRequest: {
    require: '@codeceptjs/mock-request',
    mode: process.env.MOCK_MODE || 'replay',
 },
}

Interactions between I.startMocking() and I.stopMocking() will be recorded and saved to data/requests directory.

I.startMocking() // record requests under 'Test' name
I.startMocking('users') // record requests under 'users' name

Use I.mockServer() to customize which requests should be recorded and under which name:

I.startMocking();
I.mockServer((server) => {
  // mock request only from ap1.com and api2.com and
  // store recording into two different files
  server.any('https://api1.com/*').passthrough(false).recordingName('api1');
  server.any('https://api2.com/*').passthrough(false).recordingName('api2');
});

To stop request recording/replaying use I.stopMocking().

🎥 To record HTTP interactions execute tests with MOCK_MODE environment variable set as "record":

MOCK_MODE=record npx codeceptjs run --debug

📼 To replay them launch tests without environment variable:

npx codeceptjs run --debug

Parameters

  • config

startMocking

Starts mocking of http requests. In record mode starts recording of all requests. In replay mode blocks all requests and replaces them with saved.

If inside one test you plan to record/replay requests in several places, provide recording name as the parameter.

// start mocking requests for a test
I.startMocking(); 

// start mocking requests for main page
I.startMocking('main-page');
// do actions
I.stopMocking();
I.startMocking('login-page');

To update PollyJS configuration use secon argument:

// change mode
I.startMocking('comments', { mode: 'replay' });

// override config
I.startMocking('users-loaded', {
   recordFailedRequests: true
})
Parameters
  • title any (optional, default 'Test')
  • config (optional, default {})

mockServer

Use PollyJS Server Routes API to declare mocks via callback function:

// basic usage
server.get('/api/v2/users').intercept((req, res) => {
  res.sendStatus(200).json({ users });
});

// passthrough requests to "/api/v2"
server.get('/api/v1').passthrough();

In record replay mode you can define which routes should be recorded and where to store them:

I.startMocking('mock');
I.mockServer((server) => {

  // record requests from cdn1.com and save them to data/recording/xml
  server.any('https://cdn1.com/*').passthrough(false).recordingName('xml');
  
  // record requests from cdn2.com and save them to data/recording/svg
  server.any('https://cdn2.com/*').passthrough(false).recordingName('svg');

  // record requests from /api and save them to data/recording/mock (default)
  server.any('/api/*').passthrough(false);
});
Parameters
  • configFn

recordMocking

Forces record mode for mocking. Requires mocking to be started.

I.recordMocking();

replayMocking

Forces replay mode for mocking. Requires mocking to be started.

I.replayMocking();

passthroughMocking

Forces passthrough mode for mocking. Requires mocking to be started.

I.passthroughMocking();

flushMocking

Waits for all requests handled by MockRequests to be resolved:

I.flushMocking();

stopMocking

Stops mocking requests. Must be called to save recorded requests into faile.

I.stopMocking();

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. (optional, default null)

版本与发布记录

@codeceptjs/mock-request 共发布 4 个版本,首次发布于 2020/03/20;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.3.1latest2021/11/104 年前
0.3.02020/03/296 年前
0.2.02020/03/226 年前
0.1.02020/03/206 年前

关于 @codeceptjs/mock-request 的常见问题

@codeceptjs/mock-request 是什么?

Mocking requests with PollyJS for CodeceptJS

如何安装 @codeceptjs/mock-request?

在项目目录运行 npm install @codeceptjs/mock-request,或使用 pnpm add / yarn add / bun add。

@codeceptjs/mock-request 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/codeceptjs__mock-request 是否存在。

@codeceptjs/mock-request 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@codeceptjs/mock-request 可以商用吗?

@codeceptjs/mock-request 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@codeceptjs/mock-request 的下载量有多少?

根据 npm 官方下载统计,@codeceptjs/mock-request 在 2026/10/10 – 2026/11/08 这 30 天内被下载 10,498 次,日均约 350 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@codeceptjs/mock-request 还在维护吗?

最新版本 0.3.1 发布于 2021/11/10(4 年前);至今共发布 4 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/03/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。