MockRequest
MockRequest
Section titled “MockRequest”MockRequest
Section titled “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 modeI.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 pageI.startMocking();I.amOnPage('/users');I.stopMocking();Installations
Section titled “Installations”npm i @codeceptjs/mock-request --save-devRequires Puppeteer helper or WebDriver helper enabled
Configuration
Section titled “Configuration”With Puppeteer
Section titled “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 optionshelpers: { 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
Section titled “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
đź‘» Mock Requests
Section titled “👻 Mock Requests”To intercept API requests and mock them use following API
- startMocking() - to enable request interception
- mockRequest() - to define mock in a simple way
- mockServer() - to use PollyJS server API to define complex mocks
- stopMocking() - to stop intercepting requests and disable mocks.
Calling mockRequest or mockServer will start mocking, if it was not enabled yet.
I.startMocking(); // optionallyI.mockRequest('/google-analytics/*path', 200);// return an empty successful responseI.mockRequest('GET', '/api/users', 200);// mock users apiI.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
Section titled “📼 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 modehelpers: { 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' nameI.startMocking('users') // record requests under 'users' nameUse 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 --debugParameters
Section titled “Parameters”config
flushMocking
Section titled “flushMocking”Waits for all requests handled by MockRequests to be resolved:
I.flushMocking();mockRequest
Section titled “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
Section titled “Parameters”methodstring request method. Can beGET,POST,PUT, etc orANY.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, defaultnull)
mockServer
Section titled “mockServer”Use PollyJS Server Routes API to declare mocks via callback function:
I.mockServer((server) => { // 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
Section titled “Parameters”configFn
passthroughMocking
Section titled “passthroughMocking”Forces passthrough mode for mocking. Requires mocking to be started.
I.passthroughMocking();recordMocking
Section titled “recordMocking”Forces record mode for mocking. Requires mocking to be started.
I.recordMocking();replayMocking
Section titled “replayMocking”Forces replay mode for mocking. Requires mocking to be started.
I.replayMocking();startMocking
Section titled “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 testI.startMocking();
// start mocking requests for main pageI.startMocking('main-page');// do actionsI.stopMocking();I.startMocking('login-page');To update PollyJS configuration use secon argument:
// change modeI.startMocking('comments', { mode: 'replay' });
// override configI.startMocking('users-loaded', { recordFailedRequests: true})Parameters
Section titled “Parameters”titleany (optional, default'Test')config(optional, default{})
stopMocking
Section titled “stopMocking”Stops mocking requests. Must be called to save recorded requests into faile.
I.stopMocking();