W3cubDocs

/Cypress

route2

This is an experimental feature. In order to use it, you must set the experimentalNetworkStubbing configuration option to true.

Use cy.route2() to manage the behavior of HTTP requests at the network layer.

With cy.route2(), you can:

  • stub or spy on any type of HTTP request.
  • modify an HTTP request's body, headers, and URL before it is sent to the destination server.
  • stub the response to an HTTP request, either dynamically or statically.
  • modify real HTTP responses, changing the body, headers, or HTTP status code before they are received by the browser.
  • and much more - cy.route2() gives full access to all HTTP requests at all stages.

Comparison to cy.route()

Unlike cy.route(), cy.route2():

  • can intercept all types of network requests including Fetch API, page loads, XMLHttpRequests, resource loads, etc.
  • does not require calling cy.server() before use - in fact, cy.server() does not influence cy.route2() at all.
  • does not have method set to GET by default

Usage

cy.route2(url, routeHandler?)
cy.route2(method, url, routeHandler?)
cy.route2(routeMatcher, routeHandler?)

Arguments

url (string | RegExp)

Specify the URL to match. See the documentation for `routeMatcher` to see how URLs are matched.

cy.route2('http://example.com/widgets')
cy.route2('http://example.com/widgets', { fixture: 'widgets.json' })

method (string)

Specify the HTTP method to match on.

cy.route2('POST', 'http://example.com/widgets', {
  statusCode: 200,
  body: 'it worked!'
})

routeMatcher (RouteMatcher)

routeMatcher is an object used to match which incoming HTTP requests will be handled by this route.

All properties are optional. All properties that are set must match for the route to handle a request. If a string is passed to any property, it will be glob-matched against the request using minimatch.The available routeMatcher properties are listed below:

{
  /**
   * Match against the username and password used in HTTP Basic authentication.
   */
  auth?: { username: string | RegExp, password: string | RegExp }
  /**
   * Match against HTTP headers on the request.
   */
  headers?: {
    [name: string]: string | RegExp
  }
  /**
   * Match against the requested HTTP hostname.
   */
  hostname?: string | RegExp
  /**
   * If 'true', only HTTPS requests will be matched.
   * If 'false', only HTTP requests will be matched.
   */
  https?: boolean
  /**
   * Match against the request's HTTP method.
   * @default '*'
   */
  method?: string | RegExp
  /**
   * Match on request path after the hostname, including query params.
   */
  path?: string | RegExp
  /**
   * Matches like 'path', but without query params.
   */
  pathname?: string | RegExp
  /**
   * Match based on requested port, or pass an array of ports
   * to match against any in that array.
   */
  port?: number | number[]
  /**
   * Match on parsed querystring parameters.
   */
  query?: {
    [key: string]: string | RegExp
  }
  /**
   * Match against the full request URL.
   * If a string is passed, it will be used as a substring match,
   * not an equality match.
   */
  url?: string | RegExp
}

routeMatcher usage examples:

cy.route2({
  pathname: '/search',
  query: {
    q: 'some terms'
  }
}).as('searchForTerms')
// this 'cy.wait' will only resolve once a request is made to '/search'
// with the query paramater 'q=some+terms'
cy.wait('@searchForTerms')

cy.route2({
  // this RegExp matches any URL beginning with 'http://api.example.com/widgets'
  url: /^http:\/\/api\.example\.com\/widgets/
  headers: {
    'x-requested-with': 'exampleClient'
  }
}, (req) => {
  // only requests to URLs starting with 'http://api.example.com/widgets'
  // having the header 'x-requested-with: exampleClient' will be received
})

routeHandler (string | object | Function | StaticResponse)

The routeHandler defines what will happen with a request if the `routeMatcher` matches. It can be used to statically define a response for matching requests, or a function can be passed to dynamically intercept the outgoing request.

  • If a string is passed, requests to the route will be fulfilled with that string as the body. Passing "foo" is equivalent to using a StaticResponse object with { body: "foo" }.
  • If a StaticResponse object is passed, requests to the route will be fulfilled with a response using the values supplied in the StaticResponse. A StaticResponse can define the body of the response, as well as the headers, HTTP status code, and more. See Stubbing a response with a `StaticResponse` object for an example of how this is used.
  • If an object with no StaticResponse keys is passed, it will be sent as a JSON response body. For example, passing { foo: 'bar' } is equivalent to passing { body: { foo: 'bar' } }.
  • If a function callback is passed, it will be called whenever a request matching this route is received, with the first parameter being the request object. From inside the callback, you can modify the outgoing request, send a response, access the real response, and much more. See Intercepting a request and Intercepting a response for examples of dynamic interception.

Yields

  • cy.route2() yields null.
  • cy.route2() can be aliased, but otherwise cannot be chained further.
  • Waiting on an aliased cy.route2() route using cy.wait() will yield an object that contains information about the matching request/response cycle. See Using the yielded object for examples of how to use this object.

Examples

Waiting on a request

Use cy.wait() with cy.route2() aliases to wait for the request/response cycle to complete.

With URL

cy.route2('http://example.com/settings').as('getSettings')
// once a request to http://example.com/settings responds, this 'cy.wait' will resolve
cy.wait('@getSettings')

With `RouteMatcher`

cy.route2({
  url: 'http://example.com/search',
  query: { q: 'expected terms' },
}).as('search')

// once any type of request to http://example.com/search with a querystring containing
// 'q=expected+terms' responds, this 'cy.wait' will resolve
cy.wait('@search')

Using the yielded object

Using cy.wait() on a cy.route2() route alias yields an object which represents the request/response cycle:

cy.wait('@someRoute').then((request) => {
  // 'request' is an object with properties 'id', 'request' and 'response'
})

You can chain .its() and .should() to assert against request/response cycles:

// assert that a request to this route was made with a body that included 'user'
cy.wait('@someRoute').its('request.body').should('include', 'user')

// assert that a request to this route received a response with HTTP status 500
cy.wait('@someRoute').its('response.statusCode').should('eq', 500)

// assert that a request to this route received a response body that includes 'id'
cy.wait('@someRoute').its('response.body').should('include', 'id')

Aliasing individual requests

Aliases can be set on a per-request basis by setting the alias property of the intercepted request:

cy.route2('POST', '/graphql', (req) => {
  if (req.body.includes('mutation')) {
    req.alias = 'gqlMutation'
  }
})

// assert that a matching request has been made
cy.wait('@gqlMutation')

Stubbing a response

With a string

// requests to '/update' will be fulfilled with a body of "success"
cy.route2('/update', 'success')

With a fixture

// requests to '/users.json' will be fulfilled
// with the contents of the "users.json" fixture
cy.route2('/users.json', { fixture: 'users.json' })

With a StaticResponse object

A StaticResponse object represents a response to an HTTP request, and can be used to stub routes:

const staticResponse = { /* some StaticResponse properties here... */ }

cy.route2('/projects', staticResponse)

Here are the available properties on StaticResponse:

{
  /**
   * Serve a fixture as the response body.
   */
  fixture?: string
  /**
   * Serve a static string/JSON object as the response body.
   */
  body?: string | object | object[]
  /**
   * HTTP headers to accompany the response.
   * @default {}
   */
  headers?: { [key: string]: string }
  /**
   * The HTTP status code to send.
   * @default 200
   */
  statusCode?: number
  /**
   * If 'forceNetworkError' is truthy, Cypress will destroy the browser connection
   * and send no response. Useful for simulating a server that is not reachable.
   * Must not be set in combination with other options.
   */
  forceNetworkError?: boolean
  /**
   * Milliseconds to delay before the response is sent.
   */
  delayMs?: number
  /**
   * Kilobits per second to send 'body'.
   */
  throttleKbps?: number
}

Intercepting a request

Asserting on a request

cy.route2('POST', '/organization', (req) => {
  expect(req.body).to.include('Acme Company')
})

Modifying an outgoing request

You can use the route callback to modify the request before it is sent.

cy.route2('POST', '/login', (req) => {
  // set the request body to something different before it's sent to the destination
  req.body = 'username=janelane&password=secret123'
})

Dynamically stubbing a response

You can use the req.reply() function to dynamically control the response to a request.

cy.route2('/billing', (req) => {
  // functions on 'req' can be used to dynamically respond to a request here

  // send the request to the destination server
  req.reply()

  // respond to the request with a JSON object
  req.reply({ plan: 'starter' })

  // send the request to the destination server, and intercept the response
  req.reply((res) => {
    // 'res' represents the real destination's response
    // See "Intercepting a response" for more details and examples
  })
})

The available functions on req are:

{
  /**
   * Destroy the request and respond with a network error.
   */
  destroy(): void
  /**
   * Control the response to this request.
   * If a function is passed, the request will be sent outgoing,
   * and the function will be called with the response from the upstream server.
   * If a 'StaticResponse' is passed, it will be used as the response
   * and no request will be made to the upstream server.
   */
  reply(interceptor?: StaticResponse | HttpResponseInterceptor): void
  /**
   * Shortcut to reply to the request with a body and optional headers.
   */
  reply(body: string | object, headers?: { [key: string]: string }): void
  /**
   * Shortcut to reply to the request with an HTTP status code
   * and optional body and headers.
   */
  reply(status: number, body?: string | object, headers?: { [key: string]: string }): void
  /**
   * Respond to this request with a redirect to a new 'location'.
   * @param statusCode HTTP status code to redirect with. Default: 302
   */
  redirect(location: string, statusCode?: number): void
}

Returning a Promise

If a Promise is returned from the route callback, it will be awaited before continuing with the request.

cy.route2('POST', '/login', (req) => {
  // you could asynchronously fetch test data...
  return getLoginCredentials()
  .then((credentials) => {
    // ...and then, use it to supplement the outgoing request
    req.headers['authorization'] = credentials
  })
})

Passing a request to the next route handler

If req.reply() is not explicitly called inside of a route callback, requests will pass to the next route callback until none are left.

// you could have a top-level route2 that sets an auth token on all requests
cy.route2('http://api.company.com/', (req) => {
  req.headers['authorization'] = `token ${token}`
})

// and then another route2 that more narrowly asserts on certain requests
cy.route2('POST', 'http://api.company.com/widgets', (req) => {
  expect(req.body).to.include('analytics')
})

// a POST request to http://api.company.com/widgets would hit both
// of those callbacks in order then it would be sent out
// with the modified request headers to the real destination

Intercepting a response

Inside of a callback passed to req.reply(), you can access the destination server’s real response.

cy.route2('/integrations', (req) => {
  // req.reply() with a callback will send the request to the destination server
  req.reply((res) => {
    // 'res' represents the real destination response
    // you can manipulate 'res' before it's sent to the browser
  })
})

Asserting on a response

cy.route2('/projects', (req) => {
  req.reply((res) => {
    expect(res.body).to.include('My Project')
  })
})

Returning a Promise

If a Promise is returned from the route callback, it will be awaited before sending the response to the browser.

cy.route2('/users', (req) => {
  req.reply((res) => {
    // the response will not be sent to the browser until 'waitForSomething()' resolves
    return waitForSomething()
  })
})

Modifying an incoming response

You can use the res.send() function to dynamically control the incoming response. Also, any modifications to res will be persisted when the response is sent to the browser.

res.send() is implicitly called after the req.reply callback finishes if it has not already been called.

cy.route2('/notification', (req) => {
  req.reply((res) => {
    // replaces 'res.body' with "Success" and sends the response to the browser
    res.send('Success')

    // sends a fixture body instead of the existing 'res.body'
    res.send({ fixture: 'success.json' })

    // delays the response by 1000ms
    res.delay(1000)

    // throttles the response to 64kbps
    res.throttle(64)
  })
})

The available functions on res are:

{
  /**
    * Continue the HTTP response, merging the supplied values with the real response.
    */
  send(status: number, body?: string | number | object, headers?: { [key: string]: string }): void
  send(body: string | object, headers?: { [key: string]: string }): void
  send(staticResponse: StaticResponse): void
  /**
    * Continue the HTTP response to the browser,
    * including any modifications made to 'res'.
    */
  send(): void
  /**
    * Wait for 'delayMs' milliseconds before sending the response to the client.
    */
  delay: (delayMs: number) => IncomingHttpResponse
  /**
    * Serve the response at 'throttleKbps' kilobytes per second.
    */
  throttle: (throttleKbps: number) => IncomingHttpResponse
}

See also

© 2020 Cypress.io
Licensed under the MIT License.
https://docs.cypress.io/api/commands/route2.html