codeceptjs
Version:
Modern Era Acceptance Testing Framework for NodeJS
115 lines (70 loc) • 2.75 kB
Markdown
id: MockRequest
title: MockRequest
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
## 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][1] 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:
```js
helpers: {
Puppeteer: {
// regular Puppeteer config here
},
MockRequest: {}
}
```
The same can be done when using WebDriver helper..
### 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
```js
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
```js
I.mockRequest('GET', ['/secrets', '/v2/secrets'], 403);
```
#### Parameters
- `method` **[string][2]** request method. Can be `GET`, `POST`, `PUT`, etc or `ANY`.
- `oneOrMoreUrls` **([string][2] | [Array][3]<[string][2]>)** url(s) to mock. Can be exact URL, a pattern, or an array of URLs.
- `dataOrStatusCode` **([number][4] | [string][2] | [object][5])** status code when number provided. A response body otherwise
- `additionalData` **([string][2] | [object][5])** 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.
[1]: https://netflix.github.io/pollyjs/#/
[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object