{"__v":0,"_id":"56902be218c3920d00be8b5b","category":{"__v":60,"_id":"569002f19ebef90d0087289d","pages":["56900352769f210d00132595","5690047121fcf0190071d943","569004924719c119002ce654","569004ceb700ce0d002f4b94","569023e518c3920d00be8b37","569023f748df220d004ca215","5690240af7eb9a0d00f4465d","5690241b48df220d004ca217","5690243e48df220d004ca219","56902453741e9c0d00af2fb5","56902463efcc380d0043a5a1","5690247b18c3920d00be8b39","56902492f7eb9a0d00f4465f","569024a16c49d70d00f18075","569024b2efcc380d0043a5a3","569024cc48df220d004ca21b","569024ea18c3920d00be8b3b","5690258618c3920d00be8b3f","5690259bf7eb9a0d00f44662","569025b06c49d70d00f18077","569029b418c3920d00be8b43","569029d4f7eb9a0d00f44667","569029e8e056c80d00fdec58","569029fb48df220d004ca221","56902a1c18c3920d00be8b46","56902a45f7eb9a0d00f44669","56902a6be056c80d00fdec5a","56902a78f7eb9a0d00f4466b","56902a8848df220d004ca224","56902aa018c3920d00be8b4b","56902ace6c49d70d00f18085","56902ae0741e9c0d00af2fc6","56902aee48df220d004ca226","56902af8f7eb9a0d00f44674","56902b26efcc380d0043a5b1","56902b8148df220d004ca22a","56902ba918c3920d00be8b55","56902bb96c49d70d00f1808b","56902bc818c3920d00be8b57","56902bd518c3920d00be8b59","56902be218c3920d00be8b5b","56902bf66c49d70d00f1808e","56902c05e056c80d00fdec5d","56902c196c49d70d00f18090","56902c2648df220d004ca22d","56902c34f7eb9a0d00f44678","56902c5518c3920d00be8b5d","56902c62741e9c0d00af2fcc","56902cde48df220d004ca230","56902cea741e9c0d00af2fcf","56902d0ae056c80d00fdec60","56902d20efcc380d0043a5b4","56902d3448df220d004ca232","5696c3fbf9203821005fe2fb","5696c3fb9e2d000d00947ab0","5696c3fbf9203821005fe2fa","5697efee8d2a770d00d2fd17","569802611c4dc823005426c7","56a65c82b3ffe00d00156eaf","56f01f88332da41700f24b74"],"project":"568fde81b700ce0d002f4b43","version":"568fde82b700ce0d002f4b46","sync":{"url":"","isSync":false},"reference":false,"createdAt":"2016-01-08T18:41:53.562Z","from_sync":false,"order":1,"slug":"commands","title":"Commands"},"parentDoc":null,"project":"568fde81b700ce0d002f4b43","user":"568fffce769f210d0013258f","version":{"__v":23,"_id":"568fde82b700ce0d002f4b46","project":"568fde81b700ce0d002f4b43","createdAt":"2016-01-08T16:06:26.373Z","releaseDate":"2016-01-08T16:06:26.373Z","categories":["568fde82b700ce0d002f4b47","568ff0e504440a1700e4cbbd","569002f19ebef90d0087289d","569004f4769f210d00132599","5690056d9ebef90d008728a0","569005d394c5030d0028813a","5690067804440a1700e4cbe2","569137eb3c4f510d00ec9b92","56913815e56a790d008dbfe3","569138ba3c4f510d00ec9b93","5691392f3c4f510d00ec9b94","56913bbe72f2810d007e4cb0","56933b8d6ebadc0d005b71d2","56933b8d6ebadc0d005b71d3","569564facaa32519009c41e6","5696a319b6d61f0d00acfb40","5696a319a857080d0082e8e8","5697efe43503e40d0061f4d1","5697efe48d2a770d00d2fd16","569e9597ffccd10d00a05c59","56a7a1523d33bc2100793d5c","56a7a32ecf6d771700baeee8","56b8b0f7ddeb231700e69825"],"is_deprecated":false,"is_hidden":false,"is_beta":false,"is_stable":false,"codename":"bar","version_clean":"1.0.0","version":"1.0"},"updates":[],"next":{"pages":[],"description":""},"createdAt":"2016-01-08T21:36:34.821Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":55,"body":"[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"[Read about Network Requests first.](https://on.cypress.io/guides/network-requests-xhr)\",\n  \"title\": \"New to Cypress?\"\n}\n[/block]\n\nUse `cy.server` to control the behavior of requests and responses.\n\n***\n\n# [cy.server()](#section-default-usage)\n\nStart a server to begin routing responses to your requests.\n\n***\n\n# Options\n\nPass in an options object to change the default behavior of `cy.server`.\n\n**[cy.server(*options* )](#options-usage)**\n\n`cy.server` takes options that are used for 2 different purposes:\n\n1. As defaults which are merged into [`cy.route`](https://on.cypress.io/api/route).\n2. As configuration behavior for *all* requests.\n\nThe following options will be merged in as defaults to [`cy.route`](https://on.cypress.io/api/route)\n\nOption | Default | Notes\n--- | --- | ---\n`delay` | `0` | Default delay for responses\n`method` | `\"GET\"` | Default method to match against requests\n`status` | `200` | Default response Status code\n`headers` | `null` | Default response Headers\n`response` | `null` | Default response Body\n`onRequest` | `undefined` | Default callback function when a request is sent\n`onResponse` | `undefined` | Default callback function when a response is returned\n`onAbort` | `undefined` | Default callback function which fires anytime an XHR is aborted\n\n\nThe following options control the behavior of the server affecting all requests:\n\nOption | Default | Notes\n--- | --- | ---\n`enable` | `true` | Pass `false` to disable existing route stubs\n`force404` | `false` | Forces requests that don't match your routes to be sent back `404`.\n`urlMatchingOptions` | `{ matchBase: true }` | The default options passed to `minimatch` when using glob strings to match URLs\n`whitelist` | function | Callback function that whitelists requests from ever being logged or stubbed. By default this matches against asset-like requests such as `.js`, `.jsx`, `.html`, and `.css`\n\n***\n\n# Default Usage\n\n## Start a server\n\n[block:code]\n{\n    \"codes\": [\n        {\n            \"code\": \"cy.server()\\n\",\n            \"language\": \"javascript\"\n        }\n    ]\n}\n[/block]\n\n**After starting a server:**\n\n- Any request that does not match a `cy.route` will be sent a `404` status code.\n- Any request that matches the `options.whitelist` function will **NOT** be logged or stubbed. In other words it is \"whitelisted\" and ignored.\n- You will see requests named as `(XHR Stub)` or `(XHR)` in the Command Log.\n\n***\n\n# Options Usage\n\n## Change the defaults for upcoming `cy.route` commands\n\nBy default [`cy.route`](https://on.cypress.io/api/route) inherits its options from `cy.server`. Passing any of the following options to server will be inherited:\n\n- delay\n- method\n- status\n- headers\n- response\n- onRequest\n- onResponse\n\n[block:code]\n{\n    \"codes\": [\n        {\n            \"code\": \"cy\\n  .server({\\n    method: \\\"POST\\\",\\n    delay: 1000,\\n    status: 422,\\n    response: {}\\n  })\\n\\n  // our route command will now inherit its options\\n  // from the server. anything we pass specifically\\n  // to route will override the defaults.\\n  //\\n  // in this example our matching requests will\\n  // be delayed 1000ms and have a status of 422\\n  // but its response will be what we set in route\\n  .route(/users/, {errors: \\\"Name cannot be blank\\\"})\\n\\n\",\n            \"language\": \"javascript\"\n        }\n    ]\n}\n[/block]\n\n***\n\n## Change the default delay for all routes\n\nAdding delay can help simulate real world network latency. Normally stubbed responses return in under 20ms. Adding a delay can help you visualize how your application's state reacts to requests that are in flight.\n\n[block:code]\n{\n    \"codes\": [\n        {\n            \"code\": \"// delay each response 1500ms\\ncy.server({delay: 1500})\\n\",\n            \"language\": \"javascript\"\n        }\n    ]\n}\n[/block]\n\n***\n\n## Prevent sending 404's to unmatched requests\n\nIf you'd like Cypress to automatically send requests that do *NOT* match routes the following:\n\nStatus | Body | Headers\n--- | --- | ---\n`404` | \"\" | `null`\n\nSimply set `{force404: true}`\n\n[block:code]\n{\n    \"codes\": [\n        {\n            \"code\": \"cy\\n  .server({force404: true})\\n  .route(/activities/, \\\"fixture:activities.json\\\")\\n\",\n            \"language\": \"javascript\"\n        }\n    ]\n}\n[/block]\n\n[block:code]\n{\n    \"codes\": [\n        {\n            \"code\": \"\\n// Application Code\\n\\n$(function(){\\n  $.get(\\\"/activities\\\")\\n\\n  // this will be sent back 404 since it\\n  // does not match any of the cy.routes\\n  $.getJSON(\\\"/users.json\\\")\\n})\\n\",\n            \"language\": \"javascript\"\n        }\n    ]\n}\n[/block]\n\n***\n\n## Change the default response headers for all routes\n\nWhen you stub requests, you can automatically control their response headers.\n\n[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"Cypress automatically sets `Content-Length` and `Content-Type` based on the response body you've stubbed\"\n}\n[/block]\n\nThis is useful when you want to send back meta data in the headers, such as **pagination** or **token** information.\n\n[block:code]\n{\n    \"codes\": [\n        {\n            \"code\": \"cy\\n  .server({\\n    headers: {\\n      \\\"x-token\\\": \\\"abc-123-foo-bar\\\"\\n    }\\n  })\\n  .route(\\\"GET\\\", \\\"/users/1\\\", {id: 1, name: \\\"Amanda\\\"}).as(\\\"getUser\\\")\\n  .visit(\\\"/users/1/profile\\\")\\n  .wait(\\\":::at:::getUser\\\")\\n    .its(\\\"responseHeaders\\\")\\n    .should(\\\"have.property\\\", \\\"x-token\\\", \\\"abc-123-foo-bar\\\") // true\\n\",\n            \"language\": \"javascript\"\n        }\n    ]\n}\n[/block]\n\n[block:code]\n{\n    \"codes\": [\n        {\n            \"code\": \"// Application Code\\n\\n// lets use the native XHR object\\nvar xhr = new XMLHttpRequest\\n\\nxhr.open(\\\"GET\\\", \\\"/users/1\\\")\\n\\nxhr.onload = function(){\\n  var token = this.getResponseHeader(\\\"x-token\\\")\\n  console.log(token) // => abc-123-foo-bar\\n}\\n\\nxhr.send()\\n\\n\",\n            \"language\": \"javascript\"\n        }\n    ]\n}\n[/block]\n\n***\n\n## Change the default whitelisting\n\nCypress comes with a `whitelist` function that will filter out any requests that are for static assets like `.html`, `.js`, `.jsx`, `.css`.\n\nAny request that passes the `whitelist` will be ignored - it will not be logged nor will it be stubbed in any way (even if it matches a specific `cy.route`).\n\nThe idea is that we never went to interfere with static assets that are fetched via AJAX.\n\nThe default whitelist function is:\n\n[block:code]\n{\n    \"codes\": [\n        {\n            \"code\": \"var whitelist = function(xhr){\\n  // this function receives the xhr object in question and\\n  // will whitelist if its a GET that appears to be a static resource\\n  xhr.method === \\\"GET\\\" && /\\\\.(jsx?|html|css)(\\\\?.*)?$/.test(xhr.url)\\n}\\n\",\n            \"language\": \"javascript\"\n        }\n    ]\n}\n[/block]\n\nYou can override this function with your own specific logic.\n\n[block:code]\n{\n    \"codes\": [\n        {\n            \"code\": \"cy.server({\\n  whitelist: function(xhr){\\n    // specify your own function that should return\\n    // truthy if you want this xhr to be ignored,\\n    // not logged, and not stubbed.\\n  }\\n})\\n\",\n            \"language\": \"javascript\"\n        }\n    ]\n}\n[/block]\n\nIf you would like to change the default option for **ALL** `cy.server` you [can change this option permanently](#permanently-override-default-server-options).\n\n***\n\n## Turn off the server after you've started it\n\nYou can disable all stubbing and its effects and restore to the default behavior as a test is running.\n\n[block:code]\n{\n    \"codes\": [\n        {\n            \"code\": \"cy\\n  .server()\\n  .route(\\\"POST\\\", /users/, {}).as(\\\"createUser\\\")\\n\\n  ...\\n\\n  // this now disables stubbing routes and XHR's\\n  // will no longer show up as (XHR Stub) in the\\n  // Command Log. However routing aliases can\\n  // continue to be used and will continue to\\n  // match requests, but will not affect responses\\n  .server({enable: false})\\n\",\n            \"language\": \"javascript\"\n        }\n    ]\n}\n[/block]\n\n***\n\n# Notes\n\n## Server persists until the next test runs\n\nCypress automatically continues to persist the server and routing configuration even after a test ends. This means you can continue to use your application and still benefit from stubbing or other server configuration.\n\nHowever between tests, when a new test runs, the previous configuration is restored to a clean state. No configuration will leak between tests.\n\n***\n\n## Outstanding requests are automatically aborted between tests\n\nWhen a new test runs, any oustanding requests still in flight are automatically aborted. In fact this happens by default whether or not you've even started a `cy.server`.\n\n***\n\n## Server can be started before you `cy.visit`\n\nOftentimes your application may make initial requests immediately when it loads (such as authenticating a user). Cypress makes it possible to start your server and define routes before a [`cy.visit`](https://on.cypress.io/api/visit). Upon the next visit, the server + routes will be instantly applied before your application loads.\n\nYou can [read more about XHR strategy here](https://on.cypress.io/guides/network-requests-xhr).\n\n***\n\n# Related\n\n- [route](https://on.cypress.io/api/route)\n- [wait](https://on.cypress.io/api/wait)\n- [request](https://on.cypress.io/api/request)\n- [visit](https://on.cypress.io/api/visit)\n- [Network Requests](https://on.cypress.io/guides/network-requests-xhr)","excerpt":"Control the behavior of network requests and responses","slug":"server","type":"basic","title":"server"}

server

Control the behavior of network requests and responses

[block:callout] { "type": "info", "body": "[Read about Network Requests first.](https://on.cypress.io/guides/network-requests-xhr)", "title": "New to Cypress?" } [/block] Use `cy.server` to control the behavior of requests and responses. *** # [cy.server()](#section-default-usage) Start a server to begin routing responses to your requests. *** # Options Pass in an options object to change the default behavior of `cy.server`. **[cy.server(*options* )](#options-usage)** `cy.server` takes options that are used for 2 different purposes: 1. As defaults which are merged into [`cy.route`](https://on.cypress.io/api/route). 2. As configuration behavior for *all* requests. The following options will be merged in as defaults to [`cy.route`](https://on.cypress.io/api/route) Option | Default | Notes --- | --- | --- `delay` | `0` | Default delay for responses `method` | `"GET"` | Default method to match against requests `status` | `200` | Default response Status code `headers` | `null` | Default response Headers `response` | `null` | Default response Body `onRequest` | `undefined` | Default callback function when a request is sent `onResponse` | `undefined` | Default callback function when a response is returned `onAbort` | `undefined` | Default callback function which fires anytime an XHR is aborted The following options control the behavior of the server affecting all requests: Option | Default | Notes --- | --- | --- `enable` | `true` | Pass `false` to disable existing route stubs `force404` | `false` | Forces requests that don't match your routes to be sent back `404`. `urlMatchingOptions` | `{ matchBase: true }` | The default options passed to `minimatch` when using glob strings to match URLs `whitelist` | function | Callback function that whitelists requests from ever being logged or stubbed. By default this matches against asset-like requests such as `.js`, `.jsx`, `.html`, and `.css` *** # Default Usage ## Start a server [block:code] { "codes": [ { "code": "cy.server()\n", "language": "javascript" } ] } [/block] **After starting a server:** - Any request that does not match a `cy.route` will be sent a `404` status code. - Any request that matches the `options.whitelist` function will **NOT** be logged or stubbed. In other words it is "whitelisted" and ignored. - You will see requests named as `(XHR Stub)` or `(XHR)` in the Command Log. *** # Options Usage ## Change the defaults for upcoming `cy.route` commands By default [`cy.route`](https://on.cypress.io/api/route) inherits its options from `cy.server`. Passing any of the following options to server will be inherited: - delay - method - status - headers - response - onRequest - onResponse [block:code] { "codes": [ { "code": "cy\n .server({\n method: \"POST\",\n delay: 1000,\n status: 422,\n response: {}\n })\n\n // our route command will now inherit its options\n // from the server. anything we pass specifically\n // to route will override the defaults.\n //\n // in this example our matching requests will\n // be delayed 1000ms and have a status of 422\n // but its response will be what we set in route\n .route(/users/, {errors: \"Name cannot be blank\"})\n\n", "language": "javascript" } ] } [/block] *** ## Change the default delay for all routes Adding delay can help simulate real world network latency. Normally stubbed responses return in under 20ms. Adding a delay can help you visualize how your application's state reacts to requests that are in flight. [block:code] { "codes": [ { "code": "// delay each response 1500ms\ncy.server({delay: 1500})\n", "language": "javascript" } ] } [/block] *** ## Prevent sending 404's to unmatched requests If you'd like Cypress to automatically send requests that do *NOT* match routes the following: Status | Body | Headers --- | --- | --- `404` | "" | `null` Simply set `{force404: true}` [block:code] { "codes": [ { "code": "cy\n .server({force404: true})\n .route(/activities/, \"fixture:activities.json\")\n", "language": "javascript" } ] } [/block] [block:code] { "codes": [ { "code": "\n// Application Code\n\n$(function(){\n $.get(\"/activities\")\n\n // this will be sent back 404 since it\n // does not match any of the cy.routes\n $.getJSON(\"/users.json\")\n})\n", "language": "javascript" } ] } [/block] *** ## Change the default response headers for all routes When you stub requests, you can automatically control their response headers. [block:callout] { "type": "info", "body": "Cypress automatically sets `Content-Length` and `Content-Type` based on the response body you've stubbed" } [/block] This is useful when you want to send back meta data in the headers, such as **pagination** or **token** information. [block:code] { "codes": [ { "code": "cy\n .server({\n headers: {\n \"x-token\": \"abc-123-foo-bar\"\n }\n })\n .route(\"GET\", \"/users/1\", {id: 1, name: \"Amanda\"}).as(\"getUser\")\n .visit(\"/users/1/profile\")\n .wait(\"@getUser\")\n .its(\"responseHeaders\")\n .should(\"have.property\", \"x-token\", \"abc-123-foo-bar\") // true\n", "language": "javascript" } ] } [/block] [block:code] { "codes": [ { "code": "// Application Code\n\n// lets use the native XHR object\nvar xhr = new XMLHttpRequest\n\nxhr.open(\"GET\", \"/users/1\")\n\nxhr.onload = function(){\n var token = this.getResponseHeader(\"x-token\")\n console.log(token) // => abc-123-foo-bar\n}\n\nxhr.send()\n\n", "language": "javascript" } ] } [/block] *** ## Change the default whitelisting Cypress comes with a `whitelist` function that will filter out any requests that are for static assets like `.html`, `.js`, `.jsx`, `.css`. Any request that passes the `whitelist` will be ignored - it will not be logged nor will it be stubbed in any way (even if it matches a specific `cy.route`). The idea is that we never went to interfere with static assets that are fetched via AJAX. The default whitelist function is: [block:code] { "codes": [ { "code": "var whitelist = function(xhr){\n // this function receives the xhr object in question and\n // will whitelist if its a GET that appears to be a static resource\n xhr.method === \"GET\" && /\\.(jsx?|html|css)(\\?.*)?$/.test(xhr.url)\n}\n", "language": "javascript" } ] } [/block] You can override this function with your own specific logic. [block:code] { "codes": [ { "code": "cy.server({\n whitelist: function(xhr){\n // specify your own function that should return\n // truthy if you want this xhr to be ignored,\n // not logged, and not stubbed.\n }\n})\n", "language": "javascript" } ] } [/block] If you would like to change the default option for **ALL** `cy.server` you [can change this option permanently](#permanently-override-default-server-options). *** ## Turn off the server after you've started it You can disable all stubbing and its effects and restore to the default behavior as a test is running. [block:code] { "codes": [ { "code": "cy\n .server()\n .route(\"POST\", /users/, {}).as(\"createUser\")\n\n ...\n\n // this now disables stubbing routes and XHR's\n // will no longer show up as (XHR Stub) in the\n // Command Log. However routing aliases can\n // continue to be used and will continue to\n // match requests, but will not affect responses\n .server({enable: false})\n", "language": "javascript" } ] } [/block] *** # Notes ## Server persists until the next test runs Cypress automatically continues to persist the server and routing configuration even after a test ends. This means you can continue to use your application and still benefit from stubbing or other server configuration. However between tests, when a new test runs, the previous configuration is restored to a clean state. No configuration will leak between tests. *** ## Outstanding requests are automatically aborted between tests When a new test runs, any oustanding requests still in flight are automatically aborted. In fact this happens by default whether or not you've even started a `cy.server`. *** ## Server can be started before you `cy.visit` Oftentimes your application may make initial requests immediately when it loads (such as authenticating a user). Cypress makes it possible to start your server and define routes before a [`cy.visit`](https://on.cypress.io/api/visit). Upon the next visit, the server + routes will be instantly applied before your application loads. You can [read more about XHR strategy here](https://on.cypress.io/guides/network-requests-xhr). *** # Related - [route](https://on.cypress.io/api/route) - [wait](https://on.cypress.io/api/wait) - [request](https://on.cypress.io/api/request) - [visit](https://on.cypress.io/api/visit) - [Network Requests](https://on.cypress.io/guides/network-requests-xhr)