7.9 KiB
title, comments, description
| title | comments | description |
|---|---|---|
| server | true |
Start a server to begin routing responses to .route() and .request().
{% note info New to Cypress? %} Read about Network Requests first. {% endnote %}
Syntax
cy.server()
cy.server(options)
Usage
.server() cannot be chained off any other cy commands, so should be chained off of cy for clarity.
{% fa fa-check-circle green %} Valid Usage
cy.server()
Arguments
{% fa fa-angle-right %} options (Object)
Pass in an options object to change the default behavior of .server(). These options are used for 2 different purposes
- As defaults that are merged into
.route(). - As configuration behavior for all requests.
The following options are merged in as default options to .route()
| Option | Default | Notes |
|---|---|---|
method |
"GET" |
method to match against requests |
response |
null |
response body when stubbing routes |
status |
200 |
response status code when stubbing routes |
delay |
0 |
delay for stubbed responses (in ms) |
headers |
null |
response headers for stubbed routes |
onRequest |
undefined |
callback function when a request is sent |
onResponse |
undefined |
callback function when a response is returned |
onAbort |
undefined |
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 |
forcibly send XHR's a 404 status when the XHR's do not match any existing |
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 for .js, .jsx, .html, and .css files. |
Yields
.server() yields the Cypress server instance.
Timeout
Examples
Start Server
After starting a server:
- Any request that does not match a
.route()will be sent a404status code. - Any request that matches the
options.whitelistfunction 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.
cy.server()
Options
Change defaults for .route()
By default cy.route inherits some of its options from cy.server().
In this example, our matching requests will be delayed 1000ms and have a status of 422, but its response will be what was set in .route().
cy.server({
method: 'POST',
delay: 1000,
status: 422,
response: {}
})
cy.route('/users/', {errors: 'Name cannot be blank'})
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.
// delay each route's response 1500ms
cy.server({delay: 1500})
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 to true.
cy.server({ force404: true })
cy.route('/activities/**', 'fixture:activities.json')
// Application Code
$(function(){
$.get('/activities')
// this will be sent back 404 since it
// does not match any of the cy.routes
$.getJSON('/users.json')
})
Change the default response headers for all routes
When you stub requests, you can automatically control their response headers. This is useful when you want to send back meta data in the headers, such as pagination or token information.
{% note info %}
Cypress automatically sets Content-Length and Content-Type based on the response body you stub.
{% endnote %}
cy.server({
headers: {
'x-token': 'abc-123-foo-bar'
}
})
cy.route('GET', '/users/1', {id: 1, name: 'Amanda'}).as('getUser')
cy.visit('/users/1/profile')
cy.wait('@getUser')
.its('responseHeaders')
.should('have.property', 'x-token', 'abc-123-foo-bar') // true
// Application Code
// lets use the native XHR object
var xhr = new XMLHttpRequest
xhr.open('GET', '/users/1')
xhr.onload = function(){
var token = this.getResponseHeader('x-token')
console.log(token) // => abc-123-foo-bar
}
xhr.send()
Change the default whitelisting
.server() comes with a whitelist function that will filter out any requests that are for static assets like .html, .js, .jsx, and .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 .route()).
The idea is that we never want to interfere with static assets that are fetched via AJAX.
The default whitelist function in Cypress is:
var whitelist = function(xhr){
// this function receives the xhr object in question and
// will whitelist if its a GET that appears to be a static resource
xhr.method === 'GET' && /\.(jsx?|html|css)(\?.*)?$/.test(xhr.url)
}
You can override this function with your own specific logic.
cy.server({
whitelist: function(xhr){
// specify your own function that should return
// truthy if you want this xhr to be ignored,
// not logged, and not stubbed.
}
})
If you would like to change the default option for ALL cy.server() you can change this option permanently.
Turn off the server after you've started it
You can disable all stubbing and its effects and restore it to the default behavior as a test is running. By setting enable to false, this disables stubbing routes and XHR's will no longer show up as (XHR Stub) in the Command Log. However, routing aliases can continue to be used and will continue to match requests, but will not affect responses.
cy.server()
cy.route('POST', '/users', {}).as('createUser')
cy.server({enable: false})
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 leaks between tests.
Outstanding requests are automatically aborted between tests
When a new test runs, any outstanding 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. Upon the next visit, the server + routes will be instantly applied before your application loads.
You can read more about XHR strategy here.