{"id":24753850,"url":"https://github.com/codeceptjs/mock-request","last_synced_at":"2025-10-11T00:30:59.760Z","repository":{"id":46159121,"uuid":"248843623","full_name":"codeceptjs/mock-request","owner":"codeceptjs","description":"👻 MockRequest helper for CodeceptJS","archived":false,"fork":false,"pushed_at":"2025-05-13T08:18:27.000Z","size":69,"stargazers_count":5,"open_issues_count":0,"forks_count":2,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-09-22T18:46:31.450Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://codecept.io","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/codeceptjs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2020-03-20T20:14:09.000Z","updated_at":"2022-04-05T23:27:26.000Z","dependencies_parsed_at":"2025-05-24T16:10:17.982Z","dependency_job_id":"f1882ac5-c0d7-41c0-8546-bb6f4b9200ba","html_url":"https://github.com/codeceptjs/mock-request","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/codeceptjs/mock-request","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codeceptjs%2Fmock-request","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codeceptjs%2Fmock-request/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codeceptjs%2Fmock-request/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codeceptjs%2Fmock-request/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/codeceptjs","download_url":"https://codeload.github.com/codeceptjs/mock-request/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codeceptjs%2Fmock-request/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279005659,"owners_count":26083942,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-10T02:00:06.843Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-01-28T11:36:34.103Z","updated_at":"2025-10-11T00:30:59.476Z","avatar_url":"https://github.com/codeceptjs.png","language":"JavaScript","readme":"# MockRequest helper for CodeceptJS\n\n[![Build Status](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fcodecept-js%2Fmock-request%2Fbadge\u0026style=popout)](https://actions-badge.atrox.dev/codecept-js/mock-request/goto)\n\n\u003e Playwright engine is not supported by this helper. Use native [Playwright API to mock requests](https://codecept.io/playwright/#mocking-network-requests). \n\n👻 Implements HTTP request mocking, record \u0026 replay via [PollyJS](https://netflix.github.io/pollyjs/#/) for [CodeceptJS](https://codecept.io). \n\nUse it to:\n\n-   📼 Record \u0026 Replay HTTP requests\n-   📲 Replace server responses\n-   ⛔ Block third party integrations: analytics, chats, support systems. \n\nWorks with Puppeteer \u0026 WebDriver helpers of [CodeceptJS](https://codecept.io).\n\n## API\n\n\u003c!-- Generated by documentation.js. Update this documentation by updating the source code. --\u003e\n\n#### Table of Contents\n\n-   [MockRequest](#mockrequest)\n    -   [Installations](#installations)\n    -   [Configuration](#configuration)\n        -   [With Puppeteer](#with-puppeteer)\n        -   [With WebDriver](#with-webdriver)\n-   [Usage](#usage)\n    -   [👻 Mock Requests](#-mock-requests)\n    -   [📼 Record \u0026 Replay](#-record--replay)\n    -   [Parameters](#parameters)\n    -   [startMocking](#startmocking)\n        -   [Parameters](#parameters-1)\n    -   [mockServer](#mockserver)\n        -   [Parameters](#parameters-2)\n    -   [recordMocking](#recordmocking)\n    -   [replayMocking](#replaymocking)\n    -   [passthroughMocking](#passthroughmocking)\n    -   [flushMocking](#flushmocking)\n    -   [stopMocking](#stopmocking)\n    -   [mockRequest](#mockrequest-1)\n        -   [Parameters](#parameters-3)\n\n### MockRequest\n\nThis helper allows to **mock requests while running tests in Puppeteer or WebDriver**.\nFor instance, you can block calls to 3rd-party services like Google Analytics, CDNs.\nAnother way of using is to emulate requests from server by passing prepared data.\n\nMockRequest helper works in these [modes](https://netflix.github.io/pollyjs/#/configuration?id=mode):\n\n-   passthrough (default) - mock prefefined HTTP requests\n-   record - record all requests into a file\n-   replay - replay all recorded requests from a file\n\nCombining record/replay modes allows testing websites with large datasets. \n\nTo use in passthrough mode set rules to mock requests and they will be automatically intercepted and replaced:\n\n```js\n// default mode\nI.mockRequest('GET', '/api/users', '[]');\n```\n\nIn record-replay mode start mocking to make HTTP requests recorded/replayed, and stop when you don't need to block requests anymore:\n\n```js\n// record or replay all XHR for /users page\nI.startMocking();\nI.amOnPage('/users');\nI.stopMocking();\n```\n\n#### Installations\n\n    npm i @codeceptjs/mock-request --save-dev\n\nRequires Puppeteer helper or WebDriver helper enabled\n\n#### Configuration\n\n##### With Puppeteer\n\nEnable helper in config file:\n\n```js\nhelpers: {\n   Puppeteer: {\n     // regular Puppeteer config here\n   },\n   MockRequestHelper: {\n     require: '@codeceptjs/mock-request',\n   }\n}\n```\n\n[Polly config options](https://netflix.github.io/pollyjs/#/configuration?id=configuration) can be passed as well:\n\n```js\n// sample options\nhelpers: {\n  MockRequestHelper: {\n     require: '@codeceptjs/mock-request',\n     mode: record,\n     recordIfMissing: true,\n     recordFailedRequests: false,\n     expiresIn: null,\n     persisterOptions: {\n       keepUnusedRequests: false\n       fs: {\n         recordingsDir: './data/requests',\n       },\n    },\n  }\n}\n```\n\n* * *\n\n**TROUBLESHOOTING**: Puppeteer does not mock requests in headless mode: \n\nProblem: request mocking does not work and in debug mode you see this in output:\n\n    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.\n\nSolution: update Puppeteer config to include `--disable-web-security` arguments:\n\n```js\n Puppeteer: {\n   show: false,\n   chrome: {\n     args: [\n       '--disable-web-security',\n     ],\n   },\n },\n```\n\n* * *\n\n##### With WebDriver\n\nThis helper partially works with WebDriver. It can intercept and mock requests **only on already loaded page**.\n\n```js\nhelpers: {\n   WebDriver: {\n     // regular WebDriver config here\n   },\n   MockRequestHelper: {\n     require: '@codeceptjs/mock-request',\n   }\n}\n```\n\n\u003e Record/Replay mode is not tested in WebDriver but technically can work with [REST Persister](https://netflix.github.io/pollyjs/#/examples?id=rest-persister)\n\n### Usage\n\n#### 👻 Mock Requests\n\nTo intercept API requests and mock them use following API\n\n-   [startMocking()](#startMocking) - to enable request interception\n-   [mockRequest()](#mockRequest) - to define mock in a simple way\n-   [mockServer()](#mockServer) - to use PollyJS server API to define complex mocks\n-   [stopMocking()](#stopMocking) - to stop intercepting requests and disable mocks.\n\nCalling `mockRequest` or `mockServer` will start mocking, if it was not enabled yet.\n\n```js\nI.startMocking(); // optionally\nI.mockRequest('/google-analytics/*path', 200);\n// return an empty successful response \nI.mockRequest('GET', '/api/users', 200);\n// mock users api\nI.mockServer(server =\u003e {\n  server.get('https://server.com/api/users*').\n    intercept((req, res) =\u003e { res.status(200).json(users);\n  });\n});\nI.click('Get users);\nI.stopMocking();\n```\n\n#### 📼 Record \u0026 Replay\n\n\u003e At this moment works only with Puppeteer\n\nRecord \u0026 Replay mode allows you to record all xhr \u0026 fetch requests and save them to file.\nOn next runs those requests can be replayed. \nBy default, it stores all passed requests, but this behavior can be customized with `I.mockServer`\n\nSet mode via enironment variable, `replay` mode by default:\n\n```js\n// enable replay mode\nhelpers: {\n Puppeteer: {\n   // regular Puppeteer config here\n },\n MockRequest: {\n    require: '@codeceptjs/mock-request',\n    mode: process.env.MOCK_MODE || 'replay',\n },\n}\n```\n\nInteractions between `I.startMocking()` and `I.stopMocking()` will be recorded and saved to `data/requests` directory.\n\n```js\nI.startMocking() // record requests under 'Test' name\nI.startMocking('users') // record requests under 'users' name\n```\n\nUse `I.mockServer()` to customize which requests should be recorded and under which name:\n\n```js\nI.startMocking();\nI.mockServer((server) =\u003e {\n  // mock request only from ap1.com and api2.com and\n  // store recording into two different files\n  server.any('https://api1.com/*').passthrough(false).recordingName('api1');\n  server.any('https://api2.com/*').passthrough(false).recordingName('api2');\n});\n```\n\nTo stop request recording/replaying use `I.stopMocking()`.\n\n🎥 To record HTTP interactions execute tests with MOCK_MODE environment variable set as \"record\":\n\n    MOCK_MODE=record npx codeceptjs run --debug\n\n📼 To replay them launch tests without environment variable:\n\n    npx codeceptjs run --debug\n\n#### Parameters\n\n-   `config`  \n\n#### startMocking\n\nStarts mocking of http requests.\nIn record mode starts recording of all requests.\nIn replay mode blocks all requests and replaces them with saved.\n\nIf inside one test you plan to record/replay requests in several places, provide [recording name](https://netflix.github.io/pollyjs/#/api?id=recordingname) as the parameter.\n\n```js\n// start mocking requests for a test\nI.startMocking(); \n\n// start mocking requests for main page\nI.startMocking('main-page');\n// do actions\nI.stopMocking();\nI.startMocking('login-page');\n```\n\nTo update [PollyJS configuration](https://netflix.github.io/pollyjs/#/configuration) use secon argument:\n\n```js\n// change mode\nI.startMocking('comments', { mode: 'replay' });\n\n// override config\nI.startMocking('users-loaded', {\n   recordFailedRequests: true\n})\n```\n\n##### Parameters\n\n-   `title` **any**  (optional, default `'Test'`)\n-   `config`   (optional, default `{}`)\n\n#### mockServer\n\nUse PollyJS [Server Routes API](https://netflix.github.io/pollyjs/#/server/overview) to declare mocks via callback function:\n\n```js\n// basic usage\nserver.get('/api/v2/users').intercept((req, res) =\u003e {\n  res.sendStatus(200).json({ users });\n});\n\n// passthrough requests to \"/api/v2\"\nserver.get('/api/v1').passthrough();\n```\n\nIn record replay mode you can define which routes should be recorded and where to store them:\n\n```js\nI.startMocking('mock');\nI.mockServer((server) =\u003e {\n\n  // record requests from cdn1.com and save them to data/recording/xml\n  server.any('https://cdn1.com/*').passthrough(false).recordingName('xml');\n  \n  // record requests from cdn2.com and save them to data/recording/svg\n  server.any('https://cdn2.com/*').passthrough(false).recordingName('svg');\n\n  // record requests from /api and save them to data/recording/mock (default)\n  server.any('/api/*').passthrough(false);\n});\n```\n\n##### Parameters\n\n-   `configFn`  \n\n#### recordMocking\n\nForces record mode for mocking.\nRequires mocking to be started.\n\n```js\nI.recordMocking();\n```\n\n#### replayMocking\n\nForces replay mode for mocking.\nRequires mocking to be started.\n\n```js\nI.replayMocking();\n```\n\n#### passthroughMocking\n\nForces passthrough mode for mocking.\nRequires mocking to be started.\n\n```js\nI.passthroughMocking();\n```\n\n#### flushMocking\n\nWaits for all requests handled by MockRequests to be resolved:\n\n```js\nI.flushMocking();\n```\n\n#### stopMocking\n\nStops mocking requests.\nMust be called to save recorded requests into faile.\n\n```js\nI.stopMocking();\n```\n\n#### mockRequest\n\nMock response status\n\n```js\nI.mockRequest('GET', '/api/users', 200);\nI.mockRequest('ANY', '/secretsRoutes/*', 403);\nI.mockRequest('POST', '/secrets', { secrets: 'fakeSecrets' });\nI.mockRequest('GET', '/api/users/1', 404, 'User not found');\n```\n\nMultiple requests\n\n```js\nI.mockRequest('GET', ['/secrets', '/v2/secrets'], 403);\n```\n\n##### Parameters\n\n-   `method` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** request method. Can be `GET`, `POST`, `PUT`, etc or `ANY`.\n-   `oneOrMoreUrls` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \\| [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)\u0026lt;[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)\u003e)** url(s) to mock. Can be exact URL, a pattern, or an array of URLs.\n-   `dataOrStatusCode` **([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \\| [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \\| [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object))** status code when number provided. A response body otherwise\n-   `additionalData` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \\| [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object))** response body when a status code is set by previous parameter. (optional, default `null`)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodeceptjs%2Fmock-request","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcodeceptjs%2Fmock-request","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodeceptjs%2Fmock-request/lists"}