Gathering detailed insights and metrics for @codeceptjs/mock-request
Gathering detailed insights and metrics for @codeceptjs/mock-request
Gathering detailed insights and metrics for @codeceptjs/mock-request
Gathering detailed insights and metrics for @codeceptjs/mock-request
npm install @codeceptjs/mock-request
Typescript
Module System
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
5
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:
Works with Puppeteer & WebDriver helpers of CodeceptJS.
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:
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:
1// default mode 2I.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:
1// record or replay all XHR for /users page
2I.startMocking();
3I.amOnPage('/users');
4I.stopMocking();
npm i @codeceptjs/mock-request --save-dev
Requires Puppeteer helper or WebDriver helper enabled
Enable helper in config file:
1helpers: { 2 Puppeteer: { 3 // regular Puppeteer config here 4 }, 5 MockRequestHelper: { 6 require: '@codeceptjs/mock-request', 7 } 8}
Polly config options can be passed as well:
1// sample options 2helpers: { 3 MockRequestHelper: { 4 require: '@codeceptjs/mock-request', 5 mode: record, 6 recordIfMissing: true, 7 recordFailedRequests: false, 8 expiresIn: null, 9 persisterOptions: { 10 keepUnusedRequests: false 11 fs: { 12 recordingsDir: './data/requests', 13 }, 14 }, 15 } 16}
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:
1 Puppeteer: { 2 show: false, 3 chrome: { 4 args: [ 5 '--disable-web-security', 6 ], 7 }, 8 },
This helper partially works with WebDriver. It can intercept and mock requests only on already loaded page.
1helpers: { 2 WebDriver: { 3 // regular WebDriver config here 4 }, 5 MockRequestHelper: { 6 require: '@codeceptjs/mock-request', 7 } 8}
Record/Replay mode is not tested in WebDriver but technically can work with REST Persister
To intercept API requests and mock them use following API
Calling mockRequest
or mockServer
will start mocking, if it was not enabled yet.
1I.startMocking(); // optionally
2I.mockRequest('/google-analytics/*path', 200);
3// return an empty successful response
4I.mockRequest('GET', '/api/users', 200);
5// mock users api
6I.mockServer(server => {
7 server.get('https://server.com/api/users*').
8 intercept((req, res) => { res.status(200).json(users);
9 });
10});
11I.click('Get users);
12I.stopMocking();
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:
1// enable replay mode 2helpers: { 3 Puppeteer: { 4 // regular Puppeteer config here 5 }, 6 MockRequest: { 7 require: '@codeceptjs/mock-request', 8 mode: process.env.MOCK_MODE || 'replay', 9 }, 10}
Interactions between I.startMocking()
and I.stopMocking()
will be recorded and saved to data/requests
directory.
1I.startMocking() // record requests under 'Test' name
2I.startMocking('users') // record requests under 'users' name
Use I.mockServer()
to customize which requests should be recorded and under which name:
1I.startMocking(); 2I.mockServer((server) => { 3 // mock request only from ap1.com and api2.com and 4 // store recording into two different files 5 server.any('https://api1.com/*').passthrough(false).recordingName('api1'); 6 server.any('https://api2.com/*').passthrough(false).recordingName('api2'); 7});
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
config
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.
1// start mocking requests for a test
2I.startMocking();
3
4// start mocking requests for main page
5I.startMocking('main-page');
6// do actions
7I.stopMocking();
8I.startMocking('login-page');
To update PollyJS configuration use secon argument:
1// change mode
2I.startMocking('comments', { mode: 'replay' });
3
4// override config
5I.startMocking('users-loaded', {
6 recordFailedRequests: true
7})
title
any (optional, default 'Test'
)config
(optional, default {}
)Use PollyJS Server Routes API to declare mocks via callback function:
1// basic usage 2server.get('/api/v2/users').intercept((req, res) => { 3 res.sendStatus(200).json({ users }); 4}); 5 6// passthrough requests to "/api/v2" 7server.get('/api/v1').passthrough();
In record replay mode you can define which routes should be recorded and where to store them:
1I.startMocking('mock'); 2I.mockServer((server) => { 3 4 // record requests from cdn1.com and save them to data/recording/xml 5 server.any('https://cdn1.com/*').passthrough(false).recordingName('xml'); 6 7 // record requests from cdn2.com and save them to data/recording/svg 8 server.any('https://cdn2.com/*').passthrough(false).recordingName('svg'); 9 10 // record requests from /api and save them to data/recording/mock (default) 11 server.any('/api/*').passthrough(false); 12});
configFn
Forces record mode for mocking. Requires mocking to be started.
1I.recordMocking();
Forces replay mode for mocking. Requires mocking to be started.
1I.replayMocking();
Forces passthrough mode for mocking. Requires mocking to be started.
1I.passthroughMocking();
Waits for all requests handled by MockRequests to be resolved:
1I.flushMocking();
Stops mocking requests. Must be called to save recorded requests into faile.
1I.stopMocking();
Mock response status
1I.mockRequest('GET', '/api/users', 200); 2I.mockRequest('ANY', '/secretsRoutes/*', 403); 3I.mockRequest('POST', '/secrets', { secrets: 'fakeSecrets' }); 4I.mockRequest('GET', '/api/users/1', 404, 'User not found');
Multiple requests
1I.mockRequest('GET', ['/secrets', '/v2/secrets'], 403);
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 otherwiseadditionalData
(string | object) response body when a status code is set by previous parameter. (optional, default null
)No vulnerabilities found.
No security vulnerabilities found.