Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(net-stubbing): deprecate cy.route(), remove experimentalNetworkStubbing #3323

Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
440ce3c
docs(net-stubbing): deprecate cy.route(), remove experimentalNetworkS…
flotwig Nov 12, 2020
c8bef8d
Merge remote-tracking branch 'origin/6.0.0-release' into deprecate-cy…
flotwig Nov 16, 2020
431e0c7
Merge branch '6.0.0-release' into deprecate-cy.route-remove-experimen…
jennifer-shehane Nov 19, 2020
1deb947
Remove deprecations from migration guide - this will be better suited…
jennifer-shehane Nov 19, 2020
839ae8b
Create a new Deprecations section in 6.0 changelog to document whats …
jennifer-shehane Nov 19, 2020
0093454
Fix links to route2 that no longer exist
jennifer-shehane Nov 19, 2020
1930af3
Make the warnings from partials not look so weird (they used to have …
jennifer-shehane Nov 19, 2020
077eb7f
Remove info notes to not link to a doc that no longer has info about …
jennifer-shehane Nov 19, 2020
92a0380
Update warnings for route/server to make them more readable.
jennifer-shehane Nov 19, 2020
0e45d8f
update examples in as.md to read better + update image
jennifer-shehane Nov 19, 2020
b588846
fix title of http page
jennifer-shehane Nov 20, 2020
39028a3
Add back example of how to generate screenshot
jennifer-shehane Nov 20, 2020
86f24cb
fix typo
jennifer-shehane Nov 20, 2020
896ff7d
remove tradeoff about there being no shadow dom support
jennifer-shehane Nov 20, 2020
0e7301a
Merge branch '6.0.0-release' into deprecate-cy.route-remove-experimen…
jennifer-shehane Nov 20, 2020
cbd4daa
Merge branch '6.0.0-release' into deprecate-cy.route-remove-experimen…
jennifer-shehane Nov 23, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions source/_changelogs/5.6.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

**Features:**

- You can now dynamically add aliases for requests intercepted via {% url "`cy.route2()`" route2 %}. {% url "See an example" route2#Aliasing-individual-requests %}. Addresses {% issue 387 %}.
- You can now dynamically add aliases for requests intercepted via {% url "`cy.route2()`" http %}. {% url "See an example" http#Aliasing-individual-requests %}. Addresses {% issue 387 %}.
- You can now run all integration specs or all component specs separately (or a filtered list of specs) by clicking the appropriate button in the Test Runner in the *Tests* tab. Addresses {% issue 8203 %}.
- Added a new modifier syntax to {% url "`cy.type()`" type %}. You can now type shortcuts like `{ctrl+z}`. Addressed in {% issue 5694 %}.
- We now show a modal with release notes when available when there is a new version of Cypress. Addressed in {% issue 9006 %}.
Expand All @@ -14,9 +14,9 @@

- Fixed a regression introduced in {% url "4.12.0" changelog#4-12-0 %} where snapshotting caused images to load too many times. Fixes {% issue 8679 %}.
- Using {% url "`cy.visit()`" visit %} on sites with `content-type` of `text-html` followed by parameters (like `text/html;charset=utf-8`) will no longer throw an error about visiting a site with an invalid content-type. Fixes {% issue 8506 %}
- The `Cannot access 'continueSent' before initialization` error will no longer throw when using {% url "`cy.route2()`" route2 %}. Fixes {% issue 8926 %}.
- Awaiting a request body when providing a static response stub in {% url "`cy.route2()`" route2 %} should now work properly. Addressed in {% issue 9059 %}.
- The way that intercepted {% url "`cy.route2()`" route2 %} requests are displayed in the Command Log has been improved, including showing the progress bar correctly. Addresses {% issue 9053 %}.
- The `Cannot access 'continueSent' before initialization` error will no longer throw when using {% url "`cy.route2()`" http %}. Fixes {% issue 8926 %}.
- Awaiting a request body when providing a static response stub in {% url "`cy.route2()`" http %} should now work properly. Addressed in {% issue 9059 %}.
- The way that intercepted {% url "`cy.route2()`" http %} requests are displayed in the Command Log has been improved, including showing the progress bar correctly. Addresses {% issue 9053 %}.
- The `Cannot read property 'replace' of undefined` error will no longer throw when attempting to generate the stack trace from an error thrown in the application. Fixes {% issue 7915 %}.
- Stack traces in the Command Log originating from application errors where the location is unavailable will no longer show as a clickable link to open in IDE. Fixes {% issue 9106 %}.
- When using the `fixture:` prefix as a stubbed response to {% url "`cy.route()`" route %}, JSON fixtures containing only a number or boolean will no longer throw an error. Fixes {% issue 4899 %}.
Expand Down
15 changes: 12 additions & 3 deletions source/_changelogs/6.0.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,17 @@
**{% fa fa-exclamation-triangle red %} Please read our {% url "Migration Guide" migration-guide %} which explains the changes in more detail and how to change your code to migrate to Cypress 6.0.**

- DOM elements where the CSS style (or ancestors) are `opacity: 0` are no longer considered visible. However these are still considered {% url "actionable" interacting-with-elements %} and {% url "any action commands" interacting-with-elements#Actionability %} used to interact with the element will perform the action. This matches browser's implementation on how they regard elements with `opacity: 0`. Addresses {% issue 4474 %}.
- We removed several deprecation errors around APIs that were removed in versions of Cypress prior to 4.0.0. For a full list of all APIs affected see {% issue 8946 %}.
- We updated our HTTP status codes and reason phrases to match Node.js `http.STATUS_CODES`. If you have code that relies on a reason phrase returned, then this could affect you. Addressed in {% issue 8969 %}.
- `cy.route2()` was renamed to {% url "`cy.http()`" http %} and will be removed in a future release. While technically not a breaking change, we encourage you to update usages of `cy.route2()` to use {% url "`cy.http()`" http %}. Addressed in {% issue 9182 %}.
- The `experimentalNetworkStubbing` option has been removed and made the default behavior. You can safely removed this configuration option. Addressed in {% issue 9185 %}.
- We removed several deprecation errors around APIs that were removed in versions of Cypress prior to 4.0.0. This will not cause any changes for anyone upgrading from a 4.0+ version of Cypress. For a full list of all APIs affected see {% issue 8946 %}.
- We updated our HTTP status codes and reason phrases to match Node.js `http.STATUS_CODES`. If you have code that relies on a reason phrase, then this could affect you. Addressed in {% issue 8969 %}.

**Deprecations:**

Deprecations still work as before but will be removed from Cypress in a future release. We encourage you to update your code now to remove uses of deprecations.

- `cy.server()` and `cy.route()` have been deprecated. In a future release, support for `cy.server()` and `cy.route()` will be moved to a plugin. We encourage you to use {% url "`cy.http()`" http %} instead. Addressed in {% issue 9185 %}.
- `experimentalFetchPolyfill` has been deprecated. We encourage you to use {% url "`cy.http()`" http %} to intercept requests using the Fetch API instead.
- `cy.route2()` was renamed to {% url "`cy.http()`" http %}. We encourage you to update usages of `cy.route2()` to use {% url "`cy.http()`" http %}. Addressed in {% issue 9182 %}.

**Features:**

Expand All @@ -20,6 +28,7 @@
**Documentation Changes:**

- Our {% url "Migration Guide" migration-guide %} has a new section for 6.0 migration.
- Many of our docs examples have been updated to use {% url "`cy.http()`" http %} in place of `cy.route()` including our {% url "Network Requests" network-requests %} doc.

**Misc:**

Expand Down
10 changes: 7 additions & 3 deletions source/_partial/network_stubbing_warning.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
{% note danger %}
🚨 Please be aware that `cy.route()` and `cy.server()` only currently supports intercepting XMLHttpRequests. **Requests using the Fetch API and other types of network requests like page loads and `<script>` tags will not be intercepted by `cy.route()` and `cy.server()`.** You can polyfill `window.fetch` to spy on and stub requests using `cy.route()` and `cy.server()` by enabling the [experimental](https://on.cypress.io/experimental) feature `experimentalFetchPolyfill`. See {% issue 95 %} for more details and temporary workarounds.
{% note warning %}
⚠️ `cy.route()` and `cy.server()` only support intercepting XMLHttpRequests. Requests using the Fetch API and other types of network requests like page loads and `<script>` tags will not be intercepted by `cy.route()` and `cy.server()`.

Cypress also has a new [`cy.http()`](/api/commands/http.html) command that supports requests using the Fetch API and other types of network requests like page loads. For more information, check out the [`cy.http()` documentation](/api/commands/http.html).{% endnote %}
**To support requests using the Fetch API you can use one of the solutions below:**

- Use [`cy.http()`](/api/commands/http.html) which supports requests using the Fetch API and other types of network requests like page loads. See [`cy.http()`](/api/commands/http.html).
- Polyfill `window.fetch` to spy on and stub requests using `cy.route()` and `cy.server()` by enabling [`experimentalFetchPolyfill`](https://on.cypress.io/experimental). See {% issue 95 %} for more details and temporary workarounds.
{% endnote %}
3 changes: 3 additions & 0 deletions source/_partial/xhr_stubbing_deprecated.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{% note warning %}
⚠️ **`cy.server()` and `cy.route()` are deprecated in Cypress 6.0.0**. In a future release, support for `cy.server()` and `cy.route()` will be moved to a plugin. Consider using [`cy.http()`](/api/commands/http.html) instead.
{% endnote %}
22 changes: 11 additions & 11 deletions source/api/commands/as.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ Assign an alias for later use. Reference the alias later within a {% url `cy.get
**{% fa fa-check-circle green %} Correct Usage**

```javascript
cy.get('.main-nav').find('li').first().as('firstNav') // Alias first 'li' as @firstNav
cy.route('PUT', 'users', 'fx:user').as('putUser') // Alias that route as @putUser
cy.stub(api, 'onUnauth').as('unauth') // Alias that stub as @unauth
cy.spy(win, 'fetch').as('winFetch') // Alias that spy as @winFetch
cy.get('.main-nav').find('li').first().as('firstNav') // Alias element as @firstNav
cy.http('PUT', 'users').as('putUser') // Alias route as @putUser
cy.stub(api, 'onUnauth').as('unauth') // Alias stub as @unauth
cy.spy(win, 'fetch').as('winFetch') // Alias spy as @winFetch
```

**{% fa fa-exclamation-triangle red %} Incorrect Usage**
Expand Down Expand Up @@ -59,9 +59,9 @@ it('disables on click', () => {
Aliasing a route and then using {% url `cy.wait()` wait %} to wait for the aliased route.

```javascript
cy.route('PUT', 'users', 'fx:user').as('userPut')
cy.http('PUT', 'users', { fixture: 'user' }).as('putUser')
cy.get('form').submit()
cy.wait('@userPut')
cy.wait('@putUser')
.its('url').should('contain', 'users')
```

Expand Down Expand Up @@ -150,11 +150,11 @@ describe('A fixture', () => {
***Alias several routes***

```javascript
cy.route(/company/, 'fixture:company').as('companyGet')
cy.route(/roles/, 'fixture:roles').as('rolesGet')
cy.route(/teams/, 'fixture:teams').as('teamsGet')
cy.route(/users\/\d+/, 'fixture:user').as('userGet')
cy.route('PUT', /^\/users\/\d+/, 'fixture:user').as('userPut')
cy.http(/company/).as('companyGet')
cy.http(/roles/).as('rolesGet')
cy.http(/teams/).as('teamsGet')
cy.http(/users\/\d+/).as('userGet')
cy.http('PUT', /^\/users\/\d+/).as('userPut')
```

Aliases of routes display in the routes instrument panel:
Expand Down
9 changes: 4 additions & 5 deletions source/api/commands/exec.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,11 @@ cy.exec('npm run my-script').its('stdout').should('contain', 'Done running the s
### Write to a file to create a fixture from response body

```javascript
cy.server()
cy.route('POST', '/comments').as('postComment')
cy.http('POST', '/comments').as('postComment')
cy.get('.add-comment').click()
cy.wait('@postComment').then((xhr) => {
cy.exec(`echo ${JSON.stringify(xhr.responseBody)} >cypress/fixtures/comment.json`)
cy.fixture('comment.json').should('deep.eq', xhr.responseBody)
cy.wait('@postComment').then(({ response }) => {
cy.exec(`echo ${JSON.stringify(response.body)} >cypress/fixtures/comment.json`)
cy.fixture('comment.json').should('deep.eq', response.body)
Comment on lines -93 to +96
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This example doesn't work, so is not the equivalent of the previous version. The assertion seems to fail now because there are newlines in the body. (I'm still reviewing but this is one example of a change needed that I've run into)

  it('cy.route() - passes', () => {
    cy.visit('https://example.cypress.io/commands/network-requests')
    cy.server()
    cy.route('POST', '/comments').as('postComment')
    cy.get('.network-post').click()
    cy.wait('@postComment').then((xhr) => {
      cy.exec(`echo ${JSON.stringify(xhr.responseBody)} >cypress/fixtures/comment1.json`)
      cy.fixture('comment.json').should('deep.eq', xhr.responseBody)
    })
  })

  it('cy.http() - fails', () => {
    cy.visit('https://example.cypress.io/commands/network-requests')
    cy.http('POST', '**/comments').as('postComment')
    cy.get('.network-post').click()
    cy.wait('@postComment').then(({ response }) => {
      cy.exec(`echo ${JSON.stringify(response.body)} >cypress/fixtures/comment2.json`)
      cy.fixture('comment.json').should('deep.eq', response.body)
    })
  })

Screen Shot 2020-11-19 at 8 17 43 PM

})
```

Expand Down
35 changes: 8 additions & 27 deletions source/api/commands/fixture.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ cy.fixture('audio/sound.mp3', 'base64').then((mp3) => {

```javascript
cy.fixture('users').then((json) => {
cy.route('GET', '/users/**', json)
cy.http('GET', '/users/**', json)
})
```

Expand All @@ -147,51 +147,32 @@ cy.fixture('users').then((json) => {
{% url 'Check out our example recipe using `cy.fixture()` to bootstrap data for our application.' recipes#Server-Communication %}
{% endnote %}

### Using an alias to access a fixture

You can make use of aliasing, {% url `.as()` as %}, instead of working directly with the yielded data.

Using an alias provides the benefit of terseness and readability. It also makes it easier to access the data later in your tests.

```javascript
cy.fixture('users').as('usersJSON')
cy.route('GET', '/users/**', '@usersJSON')

// ...later on...

cy.get('#email').then(() => {
// we have access to this.usersJSON since it was aliased
this.usersJSON
})
```

### Modifying fixture data before using it

You can modify fixture data directly before passing it along to a route.

```javascript
cy.fixture('user').then((user) => {
user.firstName = 'Jane'
cy.route('GET', '/users/1', user).as('getUser')
cy.http('GET', '/users/1', user).as('getUser')
})

cy.visit('/users')
cy.wait('@getUser').then((xhr) => {
expect(xhr.requestBody.firstName).to.eq('Jane')
cy.wait('@getUser').then(({ request }) => {
expect(request.body.firstName).to.eq('Jane')
Comment on lines +161 to +162
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This returns undefined, when trying to drill into the request.body.prop because body is a string.

  it('cy.http() - route responses to matching requests', () => {
    cy.visit('https://example.cypress.io/commands/network-requests')
    cy.http('GET', '**/comments/*').as('getComment')
    cy.get('.network-btn').click()
    cy.wait('@getComment').then(({ response }) => {
      expect(response.body.name).to.eq('id labore ex et quam laborum')
    })
  })

Screen Shot 2020-11-20 at 1 57 39 PM

})
```

# Notes

## Shortcuts

### Using `fixture` or `fx` shortcuts
### Using the `fixture` `StaticResponse` property

Fixtures can also be referenced directly without using the `.fixture()` command by using the special keywords: `fixture:` or `fx:` within {% url `cy.route()` route %}.
Fixtures can also be referenced directly without using the `.fixture()` command by using the special property `fixture` on the {% url `cy.http()` http %} `StaticResponse` object.

```javascript
cy.route('GET', '/users/**', 'fixture:users') // this works
cy.route('GET', '/users/**', 'fx:users') // this also works
cy.http('GET', '/users/**', { fixture: 'users' })
```

## Validation
Expand Down Expand Up @@ -265,7 +246,7 @@ describe('User page', () => {

# See also

- {% url `cy.route()` route %}
- {% url `cy.http()` http %}
- {% url `.then()` then %}
- {% url 'Recipe: Bootstrapping App Test Data' recipes#Server-Communication %}
- {% url 'Fixtures' https://github.com/cypress-io/testing-workshop-cypress#fixtures %} section of the Cypress Testing Workshop
10 changes: 3 additions & 7 deletions source/api/commands/http.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
---
title: http
containerClass: experimental
title: route2
---

{% note warning %}
{% fa fa-warning orange %} **This is an experimental feature. In order to use it, you must set the {% url "`experimentalNetworkStubbing`" experiments %} configuration option to `true`.**
{% endnote %}

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

With `cy.http()`, you can:
Expand Down Expand Up @@ -486,6 +481,7 @@ The available functions on `res` are:

{% history %}
{% url "6.0.0" changelog#6-0-0 %} | Renamed `cy.route2()` to `cy.http()`.
{% url "6.0.0" changelog#6-0-0 %} | Removed `experimentalNetworkStubbing` option and made it the default behavior.
{% url "5.1.0" changelog#5-1-0 %} | Added experimental `cy.route2()` command under `experimentalNetworkStubbing` option.
{% endhistory %}

Expand All @@ -494,4 +490,4 @@ The available functions on `res` are:
* {% url "`cy.route2()` example recipes with real-world examples" https://github.com/cypress-io/cypress-example-recipes#stubbing-and-spying %}
* {% url "`cy.route()` vs `cy.route2()`" https://glebbahmutov.com/blog/cy-route-vs-route2/ %} blog post
* {% url "Smart GraphQL Stubbing in Cypress" https://glebbahmutov.com/blog/smart-graphql-stubbing/ %} blog post
* {% url "open issues for `experimentalNetworkStubbing`" https://github.com/cypress-io/cypress/issues?q=is%3Aissue+is%3Aopen+label%3Apkg%2Fnet-stubbing %} and {% url "closed issues for `experimentalNetworkStubbing`" https://github.com/cypress-io/cypress/issues?q=is%3Aissue+is%3Aclosed+label%3Apkg%2Fnet-stubbing %}
* {% url "open issues for `net stubbing`" https://github.com/cypress-io/cypress/issues?q=is%3Aissue+is%3Aopen+label%3Apkg%2Fnet-stubbing %} and {% url "closed issues for `net stubbing`" https://github.com/cypress-io/cypress/issues?q=is%3Aissue+is%3Aclosed+label%3Apkg%2Fnet-stubbing %}
7 changes: 3 additions & 4 deletions source/api/commands/its.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,13 +203,12 @@ cy.window().its('evilProp').should('not.exist')
***Get `responseBody` of aliased route***

```javascript
cy.server()
cy.route(/comments/, 'fixture:comments.json').as('getComments')
cy.http(/comments/, { fixture: 'comments.json' }).as('getComments')
cy.get('#fetch-comments').click()
cy.wait('@getComments').its('responseBody').should('deep.eq', [
cy.wait('@getComments').its('response.body').should('deep.eq', JSON.stringify([
{ id: 1, comment: 'hi' },
{ id: 2, comment: 'there' }
])
]))
Comment on lines +208 to +211
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This example also doesn't work (same as as.md) due to newlines it looks like.

it('cy.http() - route responses to matching requests', () => {
  cy.visit('https://example.cypress.io/commands/network-requests')
  cy.http('GET', '**/comments/*').as('getComment')
  cy.get('.network-btn').click()
  cy.wait('@getComment').its('response.body').should('deep.eq', JSON.stringify([
    {
      postId: 1,
      id: 1,
      name: 'id labore ex et quam laborum',
      email: '[email protected]',
      body: 'laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium',
    },
  ]))

```

The commands above will display in the Command Log as:
Expand Down
4 changes: 2 additions & 2 deletions source/api/commands/request.md
Original file line number Diff line number Diff line change
Expand Up @@ -317,9 +317,9 @@ Before sending the HTTP request, we automatically attach cookies that would have

In other words, `cy.request()` transparently performs all of the underlying functions as if it came from the browser.

## {% url `cy.server()` server %} and {% url `cy.route()` route %}
## {% url `cy.http()` http %}, {% url `cy.server()` server %}, and {% url `cy.route()` route %}

### `cy.request()` sends requests to actual endpoints, bypassing those defined using `cy.route()`
### `cy.request()` sends requests to actual endpoints, bypassing those defined using `cy.route()` or `cy.http()`

`cy.server()` and any configuration passed to {% url `cy.server()` server %} has no effect on `cy.request()`.

Expand Down
4 changes: 1 addition & 3 deletions source/api/commands/route.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ title: route

Use `cy.route()` to manage the behavior of network requests.

{% note info %}
**Note:** `cy.route()` assumes you are already familiar with core concepts such as {% url 'network requests' network-requests %}
{% endnote %}
{% partial xhr_stubbing_deprecated %}

{% partial network_stubbing_warning %}

Expand Down
4 changes: 1 addition & 3 deletions source/api/commands/server.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ title: server

Start a server to begin routing responses to {% url "`cy.route()`" route %} and to change the behavior of network requests.

{% note info %}
**Note:** `cy.server()` assumes you are already familiar with core concepts such as {% url 'network requests' network-requests %}.
{% endnote %}
{% partial xhr_stubbing_deprecated %}

{% partial network_stubbing_warning %}

Expand Down
9 changes: 4 additions & 5 deletions source/api/commands/spread.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,12 @@ Option | Default | Description
### Expand the array of aliased routes

```javascript
cy.server()
cy.route('/users/').as('getUsers')
cy.route('/activities/').as('getActivities')
cy.route('/comments/').as('getComments')
cy.http('/users/').as('getUsers')
cy.http('/activities/').as('getActivities')
cy.http('/comments/').as('getComments')
cy.wait(['@getUsers', '@getActivities', '@getComments'])
.spread((getUsers, getActivities, getComments) => {
// each XHR is now an individual argument
// each request is now an individual argument
})
```

Expand Down
2 changes: 1 addition & 1 deletion source/api/commands/submit.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ If you want the other guarantees of waiting for an element to become actionable,
***Submit a form***

```javascript
cy.route('POST', '/users', 'fixture:user').as('userSuccess')
cy.http('POST', '/users', { fixture: 'user' }).as('userSuccess')
cy.get('form').submit()
```

Expand Down
14 changes: 6 additions & 8 deletions source/api/commands/visit.md
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ Trying to change the `User-Agent`? You can set the `userAgent` as a {% url "conf

## Routing

### Prevent XHR / Ajax requests before a remote page initially loads
### Prevent requests before a remote page initially loads

One common scenario Cypress supports is visiting a remote page and also preventing any Ajax requests from immediately going out.

Expand All @@ -261,24 +261,22 @@ You may think this works:
```javascript
// this code may not work depending on implementation
cy.visit('http://localhost:8000/#/app')
cy.server()
cy.route('/users/**', 'fx:users')
cy.http('/users/**', { fixture: 'users' })
```

But if your app makes a request upon being initialized, *the above code will not work*. `cy.visit()` will resolve once its `load` event fires. The {% url `cy.server()` server %} and {% url `cy.route()` route %} commands are not processed until *after* `cy.visit()` resolves.
But if your app makes a request upon being initialized, *the above code will not work*. `cy.visit()` will resolve once its `load` event fires. The {% url `cy.http()` http %} command is not processed until *after* `cy.visit()` resolves.

Many applications will have already begun routing, initialization, and requests by the time the `cy.visit()` in the above code resolves. Therefore creating a {% url `cy.server()` server %} will happen too late, and Cypress will not process the requests.
Many applications will have already begun routing, initialization, and requests by the time the `cy.visit()` in the above code resolves. Therefore creating a {% url `cy.http()` http %} route will happen too late, and Cypress will not process the requests.

Luckily Cypress supports this use case. Reverse the order of the commands:

```javascript
// this code is probably what you want
cy.server()
cy.route('/users/**', {...})
cy.http('/users/**', {...})
cy.visit('http://localhost:8000/#/app')
```

Cypress will automatically apply the server and routes to the very next `cy.visit()` and does so immediately before any of your application code runs.
Cypress will automatically apply the routes to the very next `cy.visit()` and does so immediately before any of your application code runs.

# Rules

Expand Down
Loading