mirror of
https://github.com/cypress-io/cypress.git
synced 2026-02-20 22:21:23 -06:00
Merge pull request #115 from cypress-io/docs/standardize-api
Docs/standardize api
This commit is contained in:
@@ -92,6 +92,10 @@ api:
|
||||
parent: parent.html
|
||||
parents: parents.html
|
||||
parentsuntil: parentsuntil.html
|
||||
pause: pause.html
|
||||
prev: prev.html
|
||||
prevall: prevall.html
|
||||
prevuntil: prevuntil.html
|
||||
readfile: readfile.html
|
||||
reload: reload.html
|
||||
request: request.html
|
||||
@@ -126,13 +130,14 @@ api:
|
||||
utilities:
|
||||
_: _.html
|
||||
$: $.html
|
||||
minimatch: minimatch.html
|
||||
blob: blob.html
|
||||
minimatch: minimatch.html
|
||||
moment: moment.html
|
||||
promise: promise.html
|
||||
cypress-api:
|
||||
config: config.html
|
||||
env: env.html
|
||||
cypress-commands: commands.html
|
||||
config: config.html
|
||||
cookies: cookies.html
|
||||
dom: dom.html
|
||||
env: env.html
|
||||
cypress-server: server.html
|
||||
|
||||
@@ -4,50 +4,103 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Make an assertion.
|
||||
|
||||
{% note info %}
|
||||
An alias of [`.should()`](https://on.cypress.io/api/and)
|
||||
{% endnote %}
|
||||
|
||||
{% note info New to Cypress? %}
|
||||
[Read about Making Assertions first.](https://on.cypress.io/guides/making-assertions)
|
||||
{% endnote %}
|
||||
|
||||
`cy.and` makes chaining together assertions easy.
|
||||
|
||||
You'd typically use `cy.and` when you are making multiple assertions about the same subject.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the current subject but (in some cases) a new subject |
|
||||
| **Timeout** | the assertion will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
|
||||
# [cy.and( *chainers* )](#chainers-usage)
|
||||
|
||||
Make an assertion about the current subject using assertion chainers.
|
||||
|
||||
# [cy.and( *chainers*, *value* )](#chainers-with-value-usage)
|
||||
|
||||
Make an assertion about the value of the current subject.
|
||||
|
||||
Some chai methods and chai-jQuery methods return a new (different) subject for chain-ability.
|
||||
|
||||
# [cy.and( *chainers*, *method*, *value* )](#chainers-with-method-and-value-usage)
|
||||
|
||||
Make an assertion about the subject by calling a method and providing a value to that method.
|
||||
|
||||
# [cy.and( *function* )](#function-usage)
|
||||
|
||||
Pass a function that can have any number of explicit assertions written within it.
|
||||
|
||||
Does not change the subject. Whatever was passed to the function is what is returned.
|
||||
|
||||
# Chainers Usage
|
||||
|
||||
## Chain assertions on the same subject
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
cy.get("button").should("have.class", "active").and("not.be.disabled")
|
||||
.and(chainers)
|
||||
.and(chainers, value)
|
||||
.and(chainers, method, value)
|
||||
.and(function() {})
|
||||
```
|
||||
|
||||
# Chainers with Value Usage
|
||||
## Usage
|
||||
|
||||
## Chain assertions on subject change
|
||||
`.and()` requires being chained off another cy command.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.get('.error').should('be.empty').and('be.hidden') // Yields '.error' el
|
||||
cy.contains('Login').and('be.visible') // Yields el containing Login
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.and('eq', '42') // Errors, cannot be chained off 'cy'
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} chainers** ***(String)***
|
||||
|
||||
Chainers that come from [Chai](https://on.cypress.io/guides/bundled-tools#chai) or [Chai-jQuery](https://on.cypress.io/guides/bundled-tools#chai-jquery)
|
||||
|
||||
**{% fa fa-angle-right %} value** ***(String)***
|
||||
|
||||
Value to assert against chainer.
|
||||
|
||||
**{% fa fa-angle-right %} method** ***(String)***
|
||||
|
||||
A method to be called on the chainer.
|
||||
|
||||
**{% fa fa-angle-right %} function** ***(Function)***
|
||||
|
||||
Pass a function that can have any number of explicit assertions within it. Whatever was passed to the function is what is yielded.
|
||||
|
||||
## Yields
|
||||
|
||||
In most cases, `.and()` yields the previous cy command's yield.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get('nav') // yields <nav>
|
||||
.should('be.visible') // yields <nav>
|
||||
.and('have.class', 'open') // yields <nav>
|
||||
```
|
||||
Although some chainers change what is yielded. In the example below, `.and()` yields the String 'sans-serif' because the chainer `have.css, 'font-family'` yields a string.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get('nav') // yields <nav>
|
||||
.should('be.visible') // yields <nav>
|
||||
.and('have.css', 'font-family') // yields 'sans-serif'
|
||||
```
|
||||
|
||||
## Timeout
|
||||
|
||||
`.and` will continue to retry the assertion to the duration of the previous cy commands `timeout` or the `defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
```javascript
|
||||
cy.get('input', {timeout: 10000}).should('have.value', '10').and('have.class', 'error')
|
||||
↲
|
||||
// timeout here will be passed down to the '.and()'
|
||||
// and it will retry for up to 10 secs
|
||||
```
|
||||
|
||||
# Examples
|
||||
|
||||
## Chainers
|
||||
|
||||
**Chain assertions on the same subject**
|
||||
|
||||
```javascript
|
||||
cy.get('button').should('have.class', 'active').and('not.be.disabled')
|
||||
```
|
||||
|
||||
## Chainers with Value
|
||||
|
||||
**Chain assertions when yield changes**
|
||||
|
||||
```html
|
||||
<!-- App Code -->
|
||||
@@ -60,44 +113,29 @@ cy.get("button").should("have.class", "active").and("not.be.disabled")
|
||||
|
||||
```javascript
|
||||
cy
|
||||
// subject is now <a>
|
||||
.get("a")
|
||||
|
||||
// assert <a> contains text: "Edit User"
|
||||
// subject is still the <a>
|
||||
.should("contain", "Edit User")
|
||||
|
||||
// assert subject has 'href' attribute
|
||||
// subject now changes to return value from the 'href' attribute
|
||||
.and("have.attr", "href")
|
||||
|
||||
// assert that the string returned from 'href'
|
||||
// matches the RegExp /users/
|
||||
// the subject is still the same string
|
||||
.and("match", /users/)
|
||||
|
||||
// assert that the string does not
|
||||
// have a '#' character within it
|
||||
.and("not.include", "#")
|
||||
.get('a')
|
||||
.should('contain', 'Edit User') // yields <a>
|
||||
.and('have.attr', 'href') // yields string value of href
|
||||
.and('match', /users/) // yields string value of href
|
||||
.and('not.include', '#') // yields string value of href
|
||||
```
|
||||
|
||||
# Chainers with Method and Value Usage
|
||||
## Chainers with Method and Value
|
||||
|
||||
## Assert the href is equal to '/users'
|
||||
**Assert the href is equal to '/users'**
|
||||
|
||||
```javascript
|
||||
// have.attr comes from chai-jquery
|
||||
cy
|
||||
.get("#header a")
|
||||
.should("have.class", "active")
|
||||
.and("have.attr", "href", "/users")
|
||||
.get('#header a')
|
||||
.should('have.class', 'active')
|
||||
.and('have.attr', 'href', '/users')
|
||||
```
|
||||
|
||||
# Function Usage
|
||||
## Function
|
||||
|
||||
## Verify length, content, and classes from multiple `<p>`
|
||||
**Verify length, content, and classes from multiple `<p>`**
|
||||
|
||||
Passing a function to `cy.and` enables you to assert on arbitrary subjects. This gives you the opportunity to *massage* what you'd like to assert on.
|
||||
Passing a function to `.and()` enables you to assert on the yielded subject. This gives you the opportunity to *massage* what you'd like to assert.
|
||||
|
||||
Just be sure *not* to include any code that has side effects in your callback function.
|
||||
|
||||
@@ -113,125 +151,62 @@ The callback function will be retried over and over again until no assertions wi
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("p")
|
||||
.should("not.be.empty")
|
||||
.get('p')
|
||||
.should('not.be.empty')
|
||||
.and(function($p){
|
||||
// should have found 3 elements
|
||||
expect($p).to.have.length(3)
|
||||
|
||||
// make sure the first contains some text content
|
||||
expect($p.first()).to.contain("Hello World")
|
||||
expect($p.first()).to.contain('Hello World')
|
||||
|
||||
// use jquery's map to grab all of their classes
|
||||
// jquery's map returns a new jquery object
|
||||
var classes = $p.map(function(i, el){
|
||||
return cy.$(el).attr("class")
|
||||
return cy.$(el).attr('class')
|
||||
})
|
||||
|
||||
// call classes.get() to make this a plain array
|
||||
expect(classes.get()).to.deep.eq([
|
||||
"text-primary",
|
||||
"text-danger",
|
||||
"text-default"
|
||||
'text-primary',
|
||||
'text-danger',
|
||||
'text-default'
|
||||
])
|
||||
})
|
||||
```
|
||||
|
||||
## Using a callback function will not change the subject
|
||||
**Using a callback function will not change what is yielded**
|
||||
|
||||
Whatever is returned in the function is ignored. Cypress always forces the command to yield the value from the previous cy command's yield (which in the example below is `<button>`)
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("button")
|
||||
.should("be.active")
|
||||
.get('button')
|
||||
.should('be.active')
|
||||
.and(function($button){
|
||||
// whatever we return here is ignored
|
||||
// as Cypress will always force the return
|
||||
// value for future commands to be the same
|
||||
// as the previous subject which is <button>
|
||||
|
||||
expect({foo: "bar"}).to.deep.eq({foo: "bar"})
|
||||
|
||||
// whatever the return value (if any) is ignored
|
||||
return {foo: "bar"}
|
||||
expect({foo: 'bar'}).to.deep.eq({foo: 'bar'})
|
||||
return {foo: 'bar'} // return is ignored, .and() yields <button>
|
||||
})
|
||||
|
||||
.then(function($button){
|
||||
// $button === <button>
|
||||
// the subject is unchanged no matter what was returned
|
||||
// do anything we want with <button>
|
||||
})
|
||||
```
|
||||
|
||||
## Assertions that change the subject
|
||||
|
||||
Sometimes using a specific chainer will automatically change the assertion subject.
|
||||
|
||||
For instance in `chai`, the method [`have.property("...")`](http://chaijs.com/api/bdd/) will automatically change the subject.
|
||||
|
||||
Additionally in [`Chai-jQuery`](https://github.com/chaijs/chai-jquery#attrname-value), the methods: `attr`, `prop`, `css`, and `data` also change the subject.
|
||||
|
||||
This allows you to utilize other `chainer` methods such as `match` when making assertions about values.
|
||||
|
||||
```javascript
|
||||
// in this example our subject changed to the string 'sans-serif' because
|
||||
// have.css("font-family") returned a string instead of the <body> element
|
||||
cy
|
||||
// subject is <body>
|
||||
.get("body")
|
||||
|
||||
// subject changes to the string return value of 'font-family'
|
||||
.should("have.css", "font-family")
|
||||
|
||||
// use match to assert the string matches a regular expression
|
||||
.and("match", /sans-serif/)
|
||||
```
|
||||
|
||||
```javascript
|
||||
// in this example our subject changed to the string '/users' because
|
||||
// have.attr, href, /users returned a string instead of the <a> element
|
||||
cy
|
||||
// subject is <a>
|
||||
.get("a")
|
||||
|
||||
// subject changes to the string 'users'
|
||||
.should("have.attr", "href", "/users")
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
## Similarities to Chai
|
||||
**Similarities to Chai**
|
||||
|
||||
If you've worked in [Chai](http://chaijs.com/) before, you will recognize that `cy.and` matches the same fluent assertion syntax.
|
||||
If you've worked in [Chai](http://chaijs.com/) before, you will recognize that `.and()` matches the same fluent assertion syntax.
|
||||
|
||||
Take this *explicit* assertion for example:
|
||||
|
||||
```javascript
|
||||
expect({foo: "bar"}).to.have.property("foo").and.eq("bar")
|
||||
expect({foo: 'bar'}).to.have.property('foo').and.eq('bar')
|
||||
```
|
||||
|
||||
`cy.and` reproduces this same assertion behavior.
|
||||
|
||||
## Can I pass options to cy.and()?
|
||||
|
||||
Options passed to the preceding command will be passed through to `cy.and`.
|
||||
|
||||
The following example is an example of increasing the `timeout` of the `cy.and`:
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("input", {timeout: 10000}) // <-- wait up to 10 seconds for this 'input' to be found
|
||||
.should("have.value", "foo") // <-- and to have the value 'foo'
|
||||
.and("have.class", "radio") // <-- and to have the class 'radio'
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy.find("input", {timeout: 10000}).should("have.value", "foo").and("have.class", "radio")
|
||||
↲
|
||||
// adding the timeout here will automatically
|
||||
// flow down to the assertions, and they will
|
||||
// be retried for up to 10 seconds
|
||||
```
|
||||
|
||||
## How do I know which assertions change the subject and which keep it the same?
|
||||
**How do I know which assertions change the subject and which keep it the same?**
|
||||
|
||||
The chainers that come from [Chai](https://on.cypress.io/guides/bundled-tools#chai) or [Chai-jQuery](https://on.cypress.io/guides/bundled-tools#chai-jquery) will always document what they return.
|
||||
|
||||
@@ -241,12 +216,14 @@ You can [read more about debugging assertions](https://on.cypress.io/guides/maki
|
||||
|
||||
# Command Log
|
||||
|
||||
## Chain assertions on the same subject
|
||||
**Chain assertions on the same subject**
|
||||
|
||||
```javascript
|
||||
.find("input[type='checkbox']")
|
||||
.should("be.checked")
|
||||
.and("not.be.disabled")
|
||||
cy
|
||||
.get('.list')
|
||||
.find('input[type="checkbox"]')
|
||||
.should('be.checked')
|
||||
.and('not.be.disabled')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -257,7 +234,7 @@ When clicking on `assert` within the command log, the console outputs the follow
|
||||
|
||||
<img width="636" alt="screen shot 2015-11-29 at 12 17 03 pm" src="https://cloud.githubusercontent.com/assets/1271364/11458702/3b6873be-9693-11e5-88f7-a928ebdac80c.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [should](https://on.cypress.io/api/should)
|
||||
- [Making Assertions](https://on.cypress.io/guides/making-assertions)
|
||||
|
||||
@@ -4,58 +4,98 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Assign an alias to a route or DOM element for later use. Reference the alias later within a [`.get()`](https://on.cypress.io/api/get) or [`.wait()`](https://on.cypress.io/api/wait) command with a `@` prefix.
|
||||
|
||||
{% note info New to Cypress? %}
|
||||
[Read about Using Aliases first.](https://on.cypress.io/guides/using-aliases)
|
||||
{% endnote %}
|
||||
|
||||
Assign an alias to a route or DOM element for use later. Reference the alias later within the [`cy.get`](https://on.cypress.io/api/get) or [`cy.wait`](https://on.cypress.io/api/wait) command with the prefix `@`.
|
||||
# Syntax
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the DOM element or route being aliased |
|
||||
| **Timeout** | the alias will retry the chain of commands before the alias assignment for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
```javascript
|
||||
.as(aliasName)
|
||||
```
|
||||
|
||||
# [cy.as( *text* )](#usage)
|
||||
## Usage
|
||||
|
||||
Create an alias to be used later, passing the name of the alias as a parameter.
|
||||
`.as()` requires being chained off another cy command that *yields* a DOM element, [`.stub()`](https://on.cypress.io/api/stub), [`.spy()`](https://on.cypress.io/api/spy) or [`.route()`](https://on.cypress.io/api/route).
|
||||
|
||||
# Usage
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
## Alias a route, then wait for that route using `@alias`
|
||||
```javascript
|
||||
cy.get('.main-nav').find('li').first().as('firstNav')
|
||||
cy.route('PUT', 'users', 'fx:user').as('putUser')
|
||||
cy.stub(api, 'onUnauth').as('unauth')
|
||||
cy.spy(win, 'fetch').as('winFetch')
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.as('foo') // Errors, cannot be chained off 'cy'
|
||||
cy.title().as('pageTitle') // Errors, 'title' yields a string
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} aliasName** ***(String)***
|
||||
|
||||
The name of the alias to be referenced later within a [`.get()`](https://on.cypress.io/api/get) or [`.wait()`](https://on.cypress.io/api/wait) command using a `@` prefix.
|
||||
|
||||
## Yields
|
||||
|
||||
`.as()` yields the DOM element or route chained from the previous command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.as()` will retry the chain of commands before the `.as()` command for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## DOM Element
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.route("PUT", /^\/users\/\d+/, "fixture:user").as("userPut")
|
||||
.get("form").submit()
|
||||
.wait("@userPut")
|
||||
.its("url").should("contain", "users")
|
||||
|
||||
.route('PUT', /^\/users\/\d+/, 'fixture:user').as('userPut')
|
||||
.get('form').submit()
|
||||
.wait('@userPut')
|
||||
.its('url').should('contain', 'users')
|
||||
```
|
||||
|
||||
## Route
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.route('PUT', 'users', 'fx:user').as('userPut')
|
||||
.get('form').submit()
|
||||
.wait('@userPut')
|
||||
.its('url').should('contain', 'users')
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
**Alias names cannot match some reserved words.**
|
||||
|
||||
Some strings are not allowed as alias names since they are reserved words in Cypress. These words include: `test`, `runnable`, `timeout`, `slow`, `skip`, and `inspect`.
|
||||
|
||||
# Command Log
|
||||
|
||||
## Alias several routes
|
||||
**Alias several routes**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.route(/company/, "fixture:company").as("companyGet")
|
||||
.route(/roles/, "fixture:roles").as("rolesGet")
|
||||
.route(/teams/, "fixture:teams").as("teamsGet")
|
||||
.route(/users\/\d+/, "fixture:user").as("userGet")
|
||||
.route("PUT", /^\/users\/\d+/, "fixture:user").as("userPut")
|
||||
.route(/company/, 'fixture:company').as('companyGet')
|
||||
.route(/roles/, 'fixture:roles').as('rolesGet')
|
||||
.route(/teams/, 'fixture:teams').as('teamsGet')
|
||||
.route(/users\/\d+/, 'fixture:user').as('userGet')
|
||||
.route('PUT', /^\/users\/\d+/, 'fixture:user').as('userPut')
|
||||
```
|
||||
|
||||
Aliases of routes display in the routes instrument panel:
|
||||
|
||||
<img width="567" alt="screen shot 2015-11-29 at 2 25 47 pm" src="https://cloud.githubusercontent.com/assets/1271364/11459470/22e31e54-96a5-11e5-8895-a6ff5f8bb973.png">
|
||||
|
||||
# Errors
|
||||
|
||||
## cy.as() cannot be aliased as: 'str'. This word is reserved.
|
||||
|
||||
Some strings are not allowed as aliases since they are reserved words in Cypress. These words include: test, runnable, timeout, slow, skip, and inspect.
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [get](https://on.cypress.io/api/get)
|
||||
- [wait](https://on.cypress.io/api/wait)
|
||||
|
||||
@@ -4,54 +4,84 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Make the DOM element found in the previous command lose focus.
|
||||
Make a focused DOM element blur.
|
||||
|
||||
**The following events are fired during blur:** `focusout`, `blur`
|
||||
# Syntax
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.blur` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
```javascript
|
||||
.blur()
|
||||
.blur(options)
|
||||
```
|
||||
|
||||
# [cy.blur()](#usage)
|
||||
## Usage
|
||||
|
||||
Blur the DOM element from the previous command.
|
||||
`.blur()` requires being chained off another cy command that *yields* a DOM element that is currently in focus.
|
||||
|
||||
# Options
|
||||
If you want to ensure an element is focused before blurring, try using [`.focus()`](https://on.cypress.io/focus) before `.blur()`
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.blur`.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
**[cy.blur( *options* )](#options-usage)**
|
||||
```javascript
|
||||
cy.get('[type="email"]').type('me@email.com').blur() // Blurs email input
|
||||
cy.get('[tabindex="1"]').focus().blur() // Blurs el with tabindex
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.blur('input') // Errors, cannot be chained off 'cy'
|
||||
cy.window().blur() // Errors, 'window' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.blur`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`force` | `false` | Forces blur, disables error checking prior to blur
|
||||
`force` | `false` | Forces blur, disables checking if el is focusable or focused
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Blur the comment input.
|
||||
`.blur()` yields the DOM element from the previous command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.blur()` will continue to look for the focusable element to blur for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Blur
|
||||
|
||||
**Blur the comment input.**
|
||||
|
||||
```javascript
|
||||
// returns the same <textarea> for further chaining
|
||||
cy.get("[name='comment']").type("Nice Product!").blur()
|
||||
cy.get('[name="comment"]').type('Nice Product!').blur()
|
||||
```
|
||||
|
||||
# Options Usage
|
||||
# Options
|
||||
|
||||
## Blur the first input, ignoring whether the input is currently focused.
|
||||
**Blur the first input, ignoring whether the input is currently focused.**
|
||||
|
||||
```javascript
|
||||
// returns the same <input> for further chaining
|
||||
cy.get("input:first").blur({force: true})
|
||||
cy.get('input:first').blur({ force: true })
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
**`.blur()` can time out because your browser did not receive any blur events.**
|
||||
|
||||
If you see this error, you may want to ensure that the main browser window is currently focused. This means not being focused in debugger or any other window when the command is run.
|
||||
|
||||
# Command Log
|
||||
|
||||
## Blur a textarea after typing.
|
||||
**Blur a textarea after typing.**
|
||||
|
||||
```javascript
|
||||
cy.get("[name='comment']").type("Nice Product!").blur()
|
||||
cy.get('[name="comment"]').focus().type('Nice Product!').blur()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -62,21 +92,7 @@ When clicking on the `blur` command within the command log, the console outputs
|
||||
|
||||
<img width="525" alt="screen shot 2015-11-27 at 1 37 53 pm" src="https://cloud.githubusercontent.com/assets/1271364/11446923/5c44a2ca-950c-11e5-8080-0dc108bc4959.png">
|
||||
|
||||
# Errors
|
||||
|
||||
## cy.blur() can only be called when there is a currently focused element.
|
||||
|
||||
There is currently no specific element that has focus. If you want to ensure focus before blurring, try using `cy.focus()` on the element before `cy.blur()`
|
||||
|
||||
## cy.blur() timed out because your browser did not receive any blur events. This is a known bug in Chrome when it is not the currently focused window.
|
||||
|
||||
If you see this error, you may want to ensure that the main browser window is currently focused. This means not being focused in debugger or any other window when the command is executed.
|
||||
|
||||
## cy.blur() can only be called on the focused element.
|
||||
|
||||
If you want to ensure focus on a specific element before blurring, try using `cy.focus()` on the element before `cy.blur()`
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [focused](https://on.cypress.io/api/focused)
|
||||
- [focus](https://on.cypress.io/api/focus)
|
||||
|
||||
@@ -4,32 +4,50 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Check the checkboxes or radios within the current subject.
|
||||
Check checkbox(es) or radio(s).
|
||||
|
||||
**The following events are fired during check:** `mousedown`, `focus`, `mouseup`, `click`
|
||||
# Syntax
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.check` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's [options](#options). |
|
||||
```javascript
|
||||
.check()
|
||||
.check(value)
|
||||
.check(values)
|
||||
.check(options)
|
||||
.check(value, options)
|
||||
.check(values, options)
|
||||
```
|
||||
|
||||
# [cy.check()](#usage)
|
||||
## Usage
|
||||
|
||||
Checks checkboxes or radios.
|
||||
`.check()` requires being chained off another cy command that *yields* a DOM element of type `checkbox` or `radio`.
|
||||
|
||||
# [cy.check( *value* )](#value-usage)
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
Checks the checkbox or radio with the matching value.
|
||||
```javascript
|
||||
cy.get('[type="checkbox"]').check() // Yields checkbox element
|
||||
cy.get('[type="radio"]').first().check() // Yields first radio element
|
||||
```
|
||||
|
||||
# [cy.check( *values* )](#values-usage)
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
Checks the checkboxes or radios with the matching values.
|
||||
```javascript
|
||||
cy.check('[type="checkbox"]') // Errors, cannot be chained off 'cy'
|
||||
cy.get('p:first').check() // Errors, '.get()' does not yield checkbox or radio
|
||||
```
|
||||
|
||||
# Options
|
||||
## Arguments
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.check`.
|
||||
**{% fa fa-angle-right %} value** ***(String)***
|
||||
|
||||
**cy.check( *options* )**
|
||||
Value of checkbox or radio that should be checked.
|
||||
|
||||
**{% fa fa-angle-right %} values** ***(Array)***
|
||||
|
||||
Values of checkboxes or radios that should be checked.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.check()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
@@ -37,50 +55,71 @@ Option | Default | Notes
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the check
|
||||
`force` | `false` | Forces check, disables error checking prior to check
|
||||
`log` | `true` | whether to display command in command log
|
||||
`multiple` | `false` | Enables serially checking multiple elements
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Check all checkboxes
|
||||
`.check()` yields the DOM element from the previous command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.check` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's options.
|
||||
|
||||
# Examples
|
||||
|
||||
## Check
|
||||
|
||||
**Check all checkboxes**
|
||||
|
||||
```javascript
|
||||
cy.get("[type='checkbox']").check()
|
||||
cy.get('[type="checkbox"]').check()
|
||||
```
|
||||
|
||||
## Check all radios
|
||||
**Check all radios**
|
||||
|
||||
```javascript
|
||||
cy.get("[type='radio']").check()
|
||||
cy.get('[type="radio"]').check()
|
||||
```
|
||||
|
||||
## Check the element with id of `saveUserName` and check it
|
||||
**Check the element with id of `saveUserName`**
|
||||
|
||||
```javascript
|
||||
cy.get("#saveUserName").check()
|
||||
cy.get('#saveUserName').check()
|
||||
```
|
||||
|
||||
# Value Usage
|
||||
## Value
|
||||
|
||||
## Check the checkbox with the value of "US"
|
||||
**Select the radio with the value of 'US'**
|
||||
|
||||
```javascript
|
||||
cy.get("input[type='checkbox']").check("US")
|
||||
cy.get('[type="radio"]').check('US')
|
||||
```
|
||||
|
||||
# Values Usage
|
||||
## Values
|
||||
|
||||
## Check the checkbox with the value of "ga" and "ca"
|
||||
**Check the checkboxes with the value of 'ga' and 'ca'**
|
||||
|
||||
```javascript
|
||||
cy.get("input[type='checkbox']").check(["ga", "ca"])
|
||||
cy.get('[type="checkbox"]').check(['ga', 'ca'])
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
**Check an invisible checkbox**
|
||||
|
||||
You can ignore Cypress' default behavior of checking that the element is visible, clickable and not disabled by passing `force: true` in the `.check()` options.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get('.action-checkboxes').should('not.be.visible') // Passes
|
||||
.check({force: true}).should('be.checked') // Passes
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## check the element with name of emailUser
|
||||
**check the element with name of 'emailUser'**
|
||||
|
||||
```javascript
|
||||
cy.get("form").find("[name='emailUser']").check()
|
||||
cy.get('form').find('[name="emailUser"]').check()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -91,7 +130,7 @@ When clicking on `check` within the command log, the console outputs the followi
|
||||
|
||||
<img width="547" alt="screen shot 2015-11-29 at 12 53 48 pm" src="https://cloud.githubusercontent.com/assets/1271364/11458927/65a2526c-9698-11e5-8b33-f59e666170e2.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [uncheck](https://on.cypress.io/api/uncheck)
|
||||
- [click](https://on.cypress.io/api/click)
|
||||
|
||||
@@ -4,36 +4,62 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the children of each DOM element in the set of matched DOM elements.
|
||||
Get the children of each DOM element within a set of DOM elements.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.children` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.children()](#usage)
|
||||
```javascript
|
||||
.children()
|
||||
.children(selector)
|
||||
.children(options)
|
||||
.children(selector, options)
|
||||
```
|
||||
|
||||
Get the children of each DOM element in the set of matched DOM elements.
|
||||
## Usage
|
||||
|
||||
# [cy.children( *selector* )](#selector-usage)
|
||||
`.children()` requires being chained off another cy command that *yields* a DOM element.
|
||||
|
||||
The `.children()` method optionally accepts a selector expression. If the selector is supplied, the DOM elements will be filtered by testing whether they match it.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# Options
|
||||
```javascript
|
||||
cy.get('nav').children() // Yield children of nav
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.children() // Errors, cannot be chained off 'cy'
|
||||
cy.location().children() // Errors, 'location' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
A selector used to filter matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.children`.
|
||||
|
||||
**cy.children( *options* )**
|
||||
**cy.children( *selector*, *options* )**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element(s)
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Get the children of the "secondary-nav"
|
||||
`.children()` yields the new DOM elements found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.children()` will continue to look for the children elements for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Children
|
||||
|
||||
**Get the children of the "secondary-nav"**
|
||||
|
||||
```html
|
||||
<ul class="primary-nav">
|
||||
@@ -56,17 +82,17 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
// returns [
|
||||
// yields [
|
||||
// <li class="services-1"></li>,
|
||||
// <li class="services-2"></li>,
|
||||
// <li class="services-3"></li>
|
||||
// ]
|
||||
cy.get("ul.secondary-nav").children()
|
||||
cy.get('ul.secondary-nav').children()
|
||||
```
|
||||
|
||||
# Selector Usage
|
||||
## Selector
|
||||
|
||||
## Get the children with class "active"
|
||||
**Get the children with class 'active'**
|
||||
|
||||
```html
|
||||
<div>
|
||||
@@ -78,16 +104,16 @@ cy.get("ul.secondary-nav").children()
|
||||
```
|
||||
|
||||
```javascript
|
||||
// returns [<li class="active">Unit Testing</li>]
|
||||
cy.get("ul").children(".active")
|
||||
// yields [<li class="active">Unit Testing</li>]
|
||||
cy.get('ul').children('.active')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Assert that there should be 8 children elements in a nav
|
||||
**Assert that there should be 8 children elements in a nav**
|
||||
|
||||
```javascript
|
||||
cy.get(".left-nav>.nav").children().should("have.length", 8)
|
||||
cy.get('.left-nav>.nav').children().should('have.length', 8)
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -98,7 +124,7 @@ When clicking on the `children` command within the command log, the console outp
|
||||
|
||||
<img width="542" alt="screen shot 2015-11-27 at 1 52 41 pm" src="https://cloud.githubusercontent.com/assets/1271364/11447071/2e9252bc-950e-11e5-9a32-e5860da89160.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [parent](https://on.cypress.io/api/parent)
|
||||
- [parents](https://on.cypress.io/api/parents)
|
||||
|
||||
@@ -4,51 +4,70 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Clears a value of an `<input>` or `<textarea>`. Under the hood this is actually a shortcut for writing:
|
||||
Clears the value of an `input` or `textarea`. An alias for `cy.type('{selectall}{backspace}')`
|
||||
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
cy.type("{selectall}{backspace}")
|
||||
.clear()
|
||||
.clear(options)
|
||||
```
|
||||
|
||||
Prior to clearing, if the element isn't currently focused, Cypress will issue a [click](https://on.cypress.io/api/click) on the element, which will cause the element to receive focus.
|
||||
## Usage
|
||||
|
||||
**The following events are fired during clear:** `keydown`, `keypress`, `textInput`, `input`, `keyup`.
|
||||
`.clear()` requires being chained off another cy command that *yields* an `input` or `textarea`.
|
||||
|
||||
`beforeinput` is *not* fired even though it is in the spec because no browser has adopted it.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the element that was typed into |
|
||||
| **Timeout** | `cy.clear` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's [options](#options).|
|
||||
```javascript
|
||||
cy.get('[type="text"]').clear() // Clear text input
|
||||
cy.get('textarea').type('Hi!').clear() // Clear textarea
|
||||
cy.focused().clear() // Clear focused input/textarea
|
||||
```
|
||||
|
||||
# [cy.clear()](#usage)
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
Clears the value of an `<input>` or `<textarea>`.
|
||||
```javascript
|
||||
cy.clear() // Errors, cannot be chained off 'cy'
|
||||
cy.get('nav').clear() // Errors, 'get' doesn't yield input or textarea
|
||||
cy.url().clear() // Errors, 'url' doesn't yield DOM element
|
||||
```
|
||||
|
||||
# Options
|
||||
## Arguments
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.clear`.
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
**cy.clear( *options* )**
|
||||
Pass in an options object to change the default behavior of `.clear`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`force` | `false` | Forces clear, disables error checking prior to clear
|
||||
`interval` | `16` | Interval which to retry type
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the type
|
||||
`interval` | `16` | Interval which to retry clear
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the clear
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Clear the input and type a new value.
|
||||
`.clear()` yields the `input` or `textarea` that was cleared.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.clear()` will continue to look for the `input` or `textarea` for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Clear
|
||||
|
||||
**Clear the input and type a new value.**
|
||||
|
||||
Prior to clearing, if the element isn't currently focused, Cypress issues a [.click()](https://on.cypress.io/api/click) on the element, which causes the element to receive focus.
|
||||
|
||||
```html
|
||||
<input name="name" value="John Doe" />
|
||||
```
|
||||
|
||||
```javascript
|
||||
// clears the existing value first before typing
|
||||
cy.get("input[name='name']").clear().type("Jane Lane")
|
||||
cy.get('input[name="name"]').clear().type('Jane Lane')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
@@ -56,7 +75,7 @@ cy.get("input[name='name']").clear().type("Jane Lane")
|
||||
## Clear the input and type a new value
|
||||
|
||||
```javascript
|
||||
cy.get("input[name='name']").clear().type("Jane Lane")
|
||||
cy.get('input[name="name"]').clear().type('Jane Lane')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -67,6 +86,8 @@ When clicking on `clear` within the command log, the console outputs the followi
|
||||
|
||||
<img width="511" alt="screen shot 2015-11-29 at 12 57 07 pm" src="https://cloud.githubusercontent.com/assets/1271364/11458940/bdc93a50-9698-11e5-8be7-ef6a0470c3ae.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [blur](https://on.cypress.io/api/blur)
|
||||
- [focus](https://on.cypress.io/api/focus)
|
||||
- [type](https://on.cypress.io/api/type)
|
||||
|
||||
@@ -4,47 +4,73 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Clears a browser cookie.
|
||||
Clear a browser cookie.
|
||||
|
||||
Cypress automatically clears all cookies **before** each test to prevent state from building up. You shouldn't need to invoke this command unless you're using it to clear a specific cookie inside a single test.
|
||||
{% note warning %}
|
||||
Cypress automatically clears all cookies *before* each test to prevent state from being shared across tests. You shouldn't need to use this command unless you're using it to clear all cookies inside a single test.
|
||||
{% endnote %}
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | `null` |
|
||||
| **Timeout** | `cy.clearCookie` will wait up for the duration of [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the automation server to process this command. |
|
||||
# Syntax
|
||||
|
||||
# [cy.clearCookie( *name* )](#usage)
|
||||
```javascript
|
||||
.clearCookie(name)
|
||||
.clearCookie(name, options)
|
||||
```
|
||||
|
||||
Clears a browser cookie by its name.
|
||||
## Usage
|
||||
|
||||
# Options
|
||||
`.clearCookie()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.clearCookie`.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
**[cy.clearCookie( *name*, *options* )](#options-usage)**
|
||||
```javascript
|
||||
cy.clearCookie('authId')
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} name** ***(String)***
|
||||
|
||||
The name of the cookie to be cleared.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.clearCookie`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the `cy.clearCookie` command to be processed
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the `.clearCookie()` command to be processed
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Clear a cookie after logging in
|
||||
`.clearCookie()` yields `null`
|
||||
|
||||
In this example, on first login our server sends us back a session cookie. After invoking `cy.clearCookie('session_id')` this clears the session cookie, and upon navigating to an unauthorized page, our server should have redirected us back to login.
|
||||
## Timeout
|
||||
|
||||
`.clearCookie()` will wait up for the duration of [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the automation server to process this command.
|
||||
|
||||
# Examples
|
||||
|
||||
## Clear Cookie
|
||||
|
||||
**Clear a cookie after logging in**
|
||||
|
||||
In this example, on first login our server sends us back a session cookie. After invoking `cy.clearCookie('session_id')` this clears the session cookie, and upon navigating to an unauthorized page, we asset that our server has redirected us back to login.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.login('bob@example.com', 'p@ssw0rd') // example of custom command
|
||||
.clearCookie('session_id')
|
||||
.visit('/dashboard') // we should be redirected back to login
|
||||
.url().should('eq', 'login')
|
||||
// assume we just logged in
|
||||
cy.contains('Login').click()
|
||||
cy.url().should('include', 'profile')
|
||||
cy.clearCookie('session_id')
|
||||
cy.visit('/dashboard') // we should be redirected back to login
|
||||
cy.url().should('include', 'login')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Clearing a cookie after setting a cookie
|
||||
**Clearing a cookie after setting a cookie**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
@@ -61,7 +87,7 @@ When clicking on `clearCookie` within the command log, the console outputs the f
|
||||
|
||||

|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [clearCookies](https://on.cypress.io/api/clearcookies)
|
||||
- [getCookie](https://on.cypress.io/api/getcookie)
|
||||
|
||||
@@ -4,47 +4,69 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Clears all of the browser cookies.
|
||||
Clear all browser cookies.
|
||||
|
||||
Cypress automatically invokes this command **before** each test to prevent state from building up. You shouldn't need to invoke this command unless you're using it to clear cookies inside a single test.
|
||||
{% note warning %}
|
||||
Cypress automatically clears all cookies *before* each test to prevent state from being shared across tests. You shouldn't need to use this command unless you're using it to clear a specific cookie inside a single test.
|
||||
{% endnote %}
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | `null` |
|
||||
| **Timeout** | `cy.clearCookies` will wait up for the duration of [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the automation server to process this command.|
|
||||
# Syntax
|
||||
|
||||
# [cy.clearCookies()](#usage)
|
||||
```javascript
|
||||
.clearCookies()
|
||||
.clearCookies(options)
|
||||
```
|
||||
|
||||
Clears all the browser cookies.
|
||||
## Usage
|
||||
|
||||
# Options
|
||||
`.clearCookies()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.clearCookies()
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.clearCookies`.
|
||||
|
||||
**[cy.clearCookies(*options* )](#options-usage)**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the `cy.clearCookies` command to be processed
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the `.clearCookies()` command to be processed
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Clear cookies after logging in
|
||||
`.clearCookies()` yields `null`
|
||||
|
||||
## Timeout
|
||||
|
||||
`.clearCookies()` will wait up for the duration of [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the automation server to process this command.
|
||||
|
||||
# Examples
|
||||
|
||||
## Clear Cookies
|
||||
|
||||
**Clear all cookies after logging in**
|
||||
|
||||
In this example, on first login our server sends us back a session cookie. After invoking `cy.clearCookies` this clears the session cookie, and upon navigating to an unauthorized page, our server should have redirected us back to login.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.login("bob@example.com", "p@ssw0rd") // example of custom command
|
||||
// assume we just logged in
|
||||
.contains('Login').click()
|
||||
.url().should('include', 'profile')
|
||||
.clearCookies()
|
||||
.visit("/dashboard") // we should be redirected back to login
|
||||
.url().should("eq", "login")
|
||||
.visit('/dashboard') // we should be redirected back to login
|
||||
.url().should('include', 'login')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Clear cookies after getting cookies
|
||||
**Clear cookies after getting cookies**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
@@ -61,7 +83,7 @@ When clicking on `clearCookies` within the command log, the console outputs the
|
||||
|
||||

|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [clearCookie](https://on.cypress.io/api/clearcookie)
|
||||
- [getCookie](https://on.cypress.io/api/getcookie)
|
||||
|
||||
@@ -4,32 +4,86 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Clears all data in local storage.
|
||||
|
||||
Cypress automatically invokes this command **before** each test to prevent state from building up. You shouldn't need to invoke this command unless you're using it to clear localStorage inside a single test.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the remote local storage object |
|
||||
| **Timeout** | *cannot timeout* |
|
||||
|
||||
# [cy.clearLocalStorage()](#usage)
|
||||
|
||||
Clear all data in local storage.
|
||||
|
||||
# [cy.clearLocalStorage( *string* )](#usage)
|
||||
{% note warning %}
|
||||
Cypress automatically runs this command *before* each test to prevent state from being shared across tests. You shouldn't need to use this command unless you're using it to clear localStorage inside a single test.
|
||||
{% endnote %}
|
||||
|
||||
Clears all keys in local storage matching the string.
|
||||
# Syntax
|
||||
|
||||
# [cy.clearLocalStorage( *RegExp* )](#usage)
|
||||
```javascript
|
||||
.clearLocalStorage()
|
||||
.clearLocalStorage(keys)
|
||||
```
|
||||
|
||||
Clears all keys in local storage matching the RegExp.
|
||||
## Usage
|
||||
|
||||
# Usage
|
||||
`.clearLocalStorage()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.clearLocalStorage()
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} keys** ***(String, RegExp)***
|
||||
|
||||
Specify keys to be cleared in local storage.
|
||||
|
||||
## Yields
|
||||
|
||||
`.clearLocalStorage()` yields the remove local storage object.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.clearLocalStorage()` will wait up for the duration of [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) to process this command.
|
||||
|
||||
# Examples
|
||||
|
||||
## Clear Local Storage
|
||||
|
||||
**Clear all local storage**
|
||||
|
||||
```javascript
|
||||
// returns local storage object
|
||||
cy.clearLocalStorage()
|
||||
```
|
||||
|
||||
## Clear Keys
|
||||
|
||||
**Clear local storage with key 'appName'**
|
||||
|
||||
```javascript
|
||||
cy.clearLocalStorage('appName')
|
||||
```
|
||||
|
||||
**Clear all local storage matching /app-/**
|
||||
|
||||
```javascript
|
||||
cy.clearLocalStorage(/app-/)
|
||||
```
|
||||
|
||||
|
||||
# Command Log
|
||||
|
||||
```javascript
|
||||
cy.clearLocalStorage(/prop1|2/).then(function(ls){
|
||||
expect(ls.getItem('prop1')).to.be.null
|
||||
expect(ls.getItem('prop2')).to.be.null
|
||||
expect(ls.getItem('prop3')).to.eq('magenta')
|
||||
})
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
|
||||
<img width="466" alt="screen shot 2017-05-24 at 3 19 15 pm" src="https://cloud.githubusercontent.com/assets/1271364/26421551/738be792-4094-11e7-9100-14937a369c7c.png">
|
||||
|
||||
When clicking on `clearLocalStorage` within the command log, the console outputs the following:
|
||||
|
||||
<img width="564" alt="screen shot 2017-05-24 at 3 19 25 pm" src="https://cloud.githubusercontent.com/assets/1271364/26421552/73b17ac0-4094-11e7-8a13-b59bc9613613.png">
|
||||
|
||||
# See also
|
||||
|
||||
- [clearCookies](https://on.cypress.io/api/clearcookies)
|
||||
|
||||
@@ -4,46 +4,57 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
`cy.click` is used to click a DOM element found in the previous command. The DOM element must be in a "clickable" state prior to the click event happening (it must be visible and not covered by another element).
|
||||
Click a DOM element.
|
||||
|
||||
Cypress automatically scrolls the element into view prior to attempting the click.
|
||||
# Syntax
|
||||
|
||||
By default, the click is issued at the exact center of the element. You can pass a [`position`](#position-usage) option to override this setting.
|
||||
```javascript
|
||||
.click()
|
||||
.click(options)
|
||||
.click(position)
|
||||
.click(position, options)
|
||||
.click(x, y)
|
||||
.click(x, y, options)
|
||||
```
|
||||
|
||||
**The following events are fired during click:** `mousedown`, `focus`, `mouseup`, `click`
|
||||
## Usage
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the existing DOM subject |
|
||||
| **Timeout** | `cy.click` will wait and retry until the element is 'clickable' for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's [options](#options) |
|
||||
`.click()` requires being chained off another cy command that *yields* a DOM element.
|
||||
|
||||
# [cy.click()](#usage)
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
Click the DOM element.
|
||||
```javascript
|
||||
cy.get('button').click() // Clicks on button
|
||||
cy.focused().click() // Clicks on el with focus
|
||||
cy.contains('Welcome').click() // Clicks on first el containing 'Welcome'
|
||||
```
|
||||
|
||||
# [cy.click( *position* )](#position-usage)
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.click('button') // Errors, cannot be chained off 'cy'
|
||||
cy.window().click() // Errors, 'window' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} position** ***(String)***
|
||||
|
||||
Clicks the element at the specified position. The `center` position is the default position. Valid positions are `topLeft`, `top`, `topRight`, `left`, `center`, `right`, `bottomLeft`, `bottom`, and `bottomRight`.
|
||||
|
||||

|
||||
|
||||
# [cy.click( *x*, *y* )](#coordinates-usage)
|
||||
**{% fa fa-angle-right %} x** ***(Number)***
|
||||
|
||||
You can pass a relative `x` and `y` coordinate which will calculate distance in pixels from the top left corner of the element and issue the click at the calculated coordinate.
|
||||
The distance in pixels from element's left to issue the click.
|
||||
|
||||
`x` and `y` must both be `Numbers`. Currently you cannot use `%` based arguments. [Open an issue](https://github.com/cypress-io/cypress/issues/new?body=**Description**%0A*Include%20a%20high%20level%20description%20of%20the%20error%20here%20including%20steps%20of%20how%20to%20recreate.%20Include%20any%20benefits%2C%20challenges%20or%20considerations.*%0A%0A**Code**%0A*Include%20the%20commands%20used*%0A%0A**Steps%20To%20Reproduce**%0A-%20%5B%20%5D%20Steps%0A-%20%5B%20%5D%20To%0A-%20%5B%20%5D%20Reproduce%2FFix%0A%0A**Additional%20Info**%0A*Include%20any%20images%2C%20notes%2C%20or%20whatever.*%0A) if you'd like this functionality.
|
||||
**{% fa fa-angle-right %} y** ***(Number)***
|
||||
|
||||
{% note warning %}
|
||||
Make sure not to issue a click outside of the width and height of the element. This will result in a `Command Timeout`
|
||||
{% endnote %}
|
||||
The distance in pixels from element's top to issue the click.
|
||||
|
||||
# Options
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.click`.
|
||||
|
||||
**[cy.click( *options* )](#options-usage)**
|
||||
**[cy.click( *position*, *options* )](#options-usage)**
|
||||
**[cy.click( *x*, *y*, *options* )](#options-usage)**
|
||||
Pass in an options object to change the default behavior of `.click`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
@@ -53,99 +64,89 @@ Option | Default | Notes
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the click
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Click the button
|
||||
`.click()` yields the DOM subject chained from the previous command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.click()` will wait until the element is in a 'clickable' state for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's options
|
||||
|
||||
# Examples
|
||||
|
||||
## Click
|
||||
|
||||
**Click the button**
|
||||
|
||||
```javascript
|
||||
// returns <button>Save</button>
|
||||
cy.get("button").click()
|
||||
// yields <button>Save</button>
|
||||
cy.get('button').click()
|
||||
```
|
||||
|
||||
# Position Usage
|
||||
## Position
|
||||
|
||||
## Specify a corner of the element to click
|
||||
**Specify a corner of the element to click**
|
||||
|
||||
Click the top right corner of the button.
|
||||
|
||||
```javascript
|
||||
// click is issued in the top right corner of the element
|
||||
cy.get("button").click("topRight")
|
||||
cy.get('button').click('topRight')
|
||||
```
|
||||
|
||||
# Coordinates Usage
|
||||
## Coordinates
|
||||
|
||||
## Specify explicit coordinates relative to the top left corner
|
||||
**Specify explicit coordinates relative to the top left corner**
|
||||
|
||||
The click below will be issued inside of the element (15px from the left and 40px from the top).
|
||||
|
||||
```javascript
|
||||
// the click will be issued inside of the element
|
||||
// 15px from the left and
|
||||
// 40px from the top
|
||||
cy.get("button").click(15, 40)
|
||||
cy.get('button').click(15, 40)
|
||||
```
|
||||
|
||||
# Options Usage
|
||||
## Options
|
||||
|
||||
## Force a click regardless of visibility or other elements in front of the element
|
||||
**Force a click regardless of visibility or other elements in front of the element**
|
||||
|
||||
This is useful when you want the click issued no matter what. Forcing a click disables the error checking that happens prior to a click.
|
||||
Forcing a click is useful when you want the click issued no matter what. Forcing a click disables checking that this element is visible and in a clickable state before clicking.
|
||||
|
||||
```javascript
|
||||
|
||||
cy.get('button').click({ force: true })
|
||||
```
|
||||
|
||||
{% note warning %}
|
||||
Be careful with this option because it allows the click to happen when it might actually be impossible for a real user to click.
|
||||
Be careful with this option! It may allow the click to happen when it would be impossible for a real user to click.
|
||||
{% endnote %}
|
||||
|
||||
**Force a click with position argument**
|
||||
|
||||
```javascript
|
||||
// this will disable the built-in logic for ensuring
|
||||
// the element is visible, and is physically clickable
|
||||
cy.get("button").click({force: true})
|
||||
cy.get('button').click('bottomLeft', { force: true })
|
||||
```
|
||||
|
||||
{% note info Dealing with hover and hidden elements %}
|
||||
**Force a click with relative coordinates**
|
||||
|
||||
```javascript
|
||||
cy.get('button').click(5, 60, { force: true })
|
||||
```
|
||||
**Hover and clicking hidden elements**
|
||||
|
||||
{% note info %}
|
||||
[Check out our example recipe on testing hover and working with hidden elements](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/hover_hidden_elements.js)
|
||||
{% endnote %}
|
||||
|
||||
## Force a click with position argument
|
||||
**Click all buttons found on the page**
|
||||
|
||||
```javascript
|
||||
cy.get("button").click("bottomLeft", {force: true})
|
||||
cy.get('button').click({ multiple: true })
|
||||
```
|
||||
|
||||
## Force a click with relative coordinates
|
||||
|
||||
```javascript
|
||||
cy.get("button").click(5, 60, {force: true})
|
||||
```
|
||||
|
||||
## Click all buttons found on the page
|
||||
|
||||
```javascript
|
||||
cy.get("button").click({multiple: true})
|
||||
```
|
||||
|
||||
# Known Issues
|
||||
|
||||
## pointer-events: none
|
||||
|
||||
Cypress does not currently factor in `pointer-events: none` in its clicking algorithm. [Open an issue](https://github.com/cypress-io/cypress/issues/new?body=**Description**%0A*Include%20a%20high%20level%20description%20of%20the%20error%20here%20including%20steps%20of%20how%20to%20recreate.%20Include%20any%20benefits%2C%20challenges%20or%20considerations.*%0A%0A**Code**%0A*Include%20the%20commands%20used*%0A%0A**Steps%20To%20Reproduce**%0A-%20%5B%20%5D%20Steps%0A-%20%5B%20%5D%20To%0A-%20%5B%20%5D%20Reproduce%2FFix%0A%0A**Additional%20Info**%0A*Include%20any%20images%2C%20notes%2C%20or%20whatever.*%0A) if you need this to be fixed.
|
||||
|
||||
## Element removal during `mousedown` or `mouseup`
|
||||
|
||||
The spec states what should happen if the element clicked is removed from the DOM during `mousedown` or `mouseup`, but Cypress is not currently factoring this in. [Open an issue](https://github.com/cypress-io/cypress/issues/new?body=**Description**%0A*Include%20a%20high%20level%20description%20of%20the%20error%20here%20including%20steps%20of%20how%20to%20recreate.%20Include%20any%20benefits%2C%20challenges%20or%20considerations.*%0A%0A**Code**%0A*Include%20the%20commands%20used*%0A%0A**Steps%20To%20Reproduce**%0A-%20%5B%20%5D%20Steps%0A-%20%5B%20%5D%20To%0A-%20%5B%20%5D%20Reproduce%2FFix%0A%0A**Additional%20Info**%0A*Include%20any%20images%2C%20notes%2C%20or%20whatever.*%0A) if you need this to be fixed.
|
||||
|
||||
## Animations
|
||||
|
||||
Unlike other testing frameworks, like Selenium, Cypress has built in logic for dealing with both CSS and JavaScript animations. Cypress will detect if an element is animating and will wait until the element reaches a clickable state. You will never deal with a situation where Cypress accidentally clicks the *wrong* element.
|
||||
|
||||
However, sometimes when dealing with 3rd party plugins that animate using JavaScript, Cypress logic to scroll an element into view can be affected. Cypress (acting like a real user) will attempt to position the element onscreen by scrolling all parent elements that need to be scrolled (just like a real user) prior to making a click. This *may* have an adverse affect if a 3rd party plugin is bound to the `scroll` event. Cypress is so fast that sometimes there are timing issues where 3rd party plugins have incorrectly calculated animations and sometimes even prevent an element from displaying altogether.
|
||||
|
||||
These situations are rare, but if you're having a difficult time getting an element to click or experiencing seemingly *random* failures, you will save *yourself hours of debugging and headache* by simply issuing the `{force: true}` option to the click or by inserting a small delay prior to the click with [`cy.wait(ms)`](https://on.cypress.io/api/wait). It is almost never worth your time trying to debug finicky animation issues caused by 3rd party plugins.
|
||||
|
||||
So far the only library we've seen cause issues with is animating KendoUI's `dropdownlist`. By using `{force: true}` or inserting a small `wait` prior to a click, these issues completely go away.
|
||||
|
||||
# Notes
|
||||
|
||||
## Events that are fired
|
||||
**Events that are fired**
|
||||
|
||||
```javascript
|
||||
cy.get("button").click()
|
||||
cy.get('button').click()
|
||||
// mousedown
|
||||
// focus
|
||||
// mouseup
|
||||
@@ -158,26 +159,44 @@ At the moment, `mouseover` and `mouseout` events are *not* fired but this will b
|
||||
|
||||
Additionally if the `mousedown` event causes the element to be removed from the DOM, the remaining events should continue to be fired, but to the resulting element left below the removed element. This has also not been implemented but will be implemented at some point.
|
||||
|
||||
## Focus is given to the first focusable element
|
||||
**Focus is given to the first focusable element**
|
||||
|
||||
Just like real browsers, clicking a `<span>`, for example, inside of a `<button>` will properly give the focus to the button, since that's what would happen in a real user scenario.
|
||||
|
||||
However, Cypress additionally handles situations where a child descendent is clicked inside of a focusable parent, but actually isn't visually inside the parent (per the CSS Object Model). In those cases if no focusable parent is found the window is given focus instead (which matches a real browser).
|
||||
|
||||
## Mousedown cancellation will not cause focus
|
||||
**Mousedown cancellation will not cause focus**
|
||||
|
||||
If the mousedown event has its default action prevented (`e.preventDefault()`) then the element will not receive focus as per the spec.
|
||||
|
||||
## Coordinates of a click
|
||||
**Coordinates of a click**
|
||||
|
||||
The coordinates of the click will be recorded the exact moment the click happens. When hovering over the `click` command, Cypress will display a red "hitbox" indicator on the snapshot showing you where the click event occurred on the page.
|
||||
|
||||
**pointer-events: none**
|
||||
|
||||
Cypress does not currently factor in `pointer-events: none` in its clicking algorithm. [Open an issue](https://github.com/cypress-io/cypress/issues/new) if you need this to be fixed.
|
||||
|
||||
**Element removal during `mousedown` or `mouseup`**
|
||||
|
||||
The spec states what should happen if the element clicked is removed from the DOM during `mousedown` or `mouseup`, but Cypress is not currently factoring this in. [Open an issue](https://github.com/cypress-io/cypress/issues/new) if you need this to be fixed.
|
||||
|
||||
**Animations**
|
||||
|
||||
Unlike other testing frameworks, like Selenium, Cypress has built in logic for dealing with both CSS and JavaScript animations. Cypress will detect if an element is animating and will wait until the element reaches a clickable state. You will never deal with a situation where Cypress accidentally clicks the *wrong* element.
|
||||
|
||||
However, sometimes when dealing with 3rd party plugins that animate using JavaScript, Cypress logic to scroll an element into view can be affected. Cypress (acting like a real user) will attempt to position the element onscreen by scrolling all parent elements that need to be scrolled (just like a real user) prior to making a click. This *may* have an adverse affect if a 3rd party plugin is bound to the `scroll` event. Cypress is so fast that sometimes there are timing issues where 3rd party plugins have incorrectly calculated animations and sometimes even prevent an element from displaying altogether.
|
||||
|
||||
These situations are rare, but if you're having a difficult time getting an element to click or experiencing seemingly *random* failures, you will save *yourself hours of debugging and headache* by simply issuing the `{force: true}` option to the click or by inserting a small delay prior to the click with [`cy.wait(ms)`](https://on.cypress.io/api/wait). It is almost never worth your time trying to debug finicky animation issues caused by 3rd party plugins.
|
||||
|
||||
So far the only library we've seen cause issues with is animating KendoUI's `dropdownlist`. By using `{force: true}` or inserting a small `wait` prior to a click, these issues completely go away.
|
||||
|
||||
# Command Log
|
||||
|
||||
## Click the button in the form that has text "Create User"
|
||||
**Click the button in the form that has text "Create User"**
|
||||
|
||||
```javascript
|
||||
cy.get("form").find("button").contains("Create User").click()
|
||||
cy.get('form').find('button').contains('Create User').click()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -188,17 +207,7 @@ When clicking on `click` within the command log, the console outputs the followi
|
||||
|
||||
<img width="759" alt="screen shot 2015-11-29 at 1 07 49 pm" src="https://cloud.githubusercontent.com/assets/1271364/11458989/4036493c-969a-11e5-8f98-377dfce1f2c1.png">
|
||||
|
||||
# Errors
|
||||
|
||||
## cy.click() can only be called on a single element.
|
||||
|
||||
If the subject passed to `cy.click()` are multiple elements, you need to write `cy.click({multiple: true})` to serially click each element one after another. Otherwise, ensure that your subject is only one element.
|
||||
|
||||
## cy.click() cannot be called on a <select> element. Use cy.select() command instead to change the value.
|
||||
|
||||
In order to work with selecting `<select>` elements, [`cy.select()`](https://on.cypress.io/api/select) will afford better options than `cy.click()`.
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [dblclick](https://on.cypress.io/api/dblclick)
|
||||
- [check](https://on.cypress.io/api/check)
|
||||
|
||||
@@ -4,63 +4,76 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
`cy.clock` overrides native global functions related to time, so you can test code using those functions in an easier, synchronous way. This includes the `setTimeout`, `clearTimeout`, `setInterval`, and `clearInterval` functions as well as controlling `Date` objects. Note that this only applies to the `top` window on a web page. It will not override the time functions on any iframes embedded on the web page.
|
||||
`.clock()` overrides native global functions related to time allowing them to be controlled synchronously via [`.tick()`](https://on.cypress.io/api/tick) or the yielded `clock` object. This includes controlling:
|
||||
|
||||
`cy.clock` automatically restores the native functions in between tests without you having to explicitly restore them. You can still manually restore the functions within a test by calling `.restore()` on the `clock` object that `cy.clock` yields.
|
||||
|
||||
`cy.clock` pairs with [`cy.tick`](https://on.cypress.io/api/tick), which moves the clock along a certain number of milliseconds.
|
||||
|
||||
Subsequent calls to `cy.clock` will yield the `clock` object without re-overriding the native time functions.
|
||||
|
||||
If you call `cy.clock` before visiting a page with [`cy.visit`](https://on.cypress.io/api/visit), the page's native global functions will be overridden on window load, before any of your app code runs, so even if `setTimeout`, for example, is called on page load, it can still be controlled via [`cy.tick`](https://on.cypress.io/api/tick). This also applies if, during the course of a test, the page under test is reloaded or changed.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | a `clock` object. See [clock API](#clock-api) |
|
||||
|
||||
# [cy.clock()](#usage)
|
||||
|
||||
Replaces `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval` and `Date` and allows them to be controlled synchronously via [`cy.tick`](https://on.cypress.io/api/tick) or the yielded `clock` object (see [clock API](#clock-api)).
|
||||
- `setTimeout`
|
||||
- `clearTimeout`
|
||||
- `setInterval`
|
||||
- `clearInterval`
|
||||
- `Date` Objects
|
||||
|
||||
The clock starts at the unix epoch (timestamp of 0). This means that when you instantiate `new Date` in your application, it will have a time of `January 1st, 1970`.
|
||||
|
||||
# [cy.clock( *now* )](#specify-the-now-timestamp)
|
||||
# Syntax
|
||||
|
||||
Same as above, but starts the clock at the specified timestamp.
|
||||
```javascript
|
||||
cy.clock()
|
||||
cy.clock(now)
|
||||
cy.clock(now, functionNames)
|
||||
cy.clock(options)
|
||||
cy.clock(now, options)
|
||||
cy.clock(now, functionNames, options)
|
||||
```
|
||||
|
||||
# [cy.clock( *now*, *functionNames* )](#specify-which-functions-to-override)
|
||||
## Usage
|
||||
|
||||
Same as above, but only overrides the functions in the array `functionNames`.
|
||||
`cy.clock()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
# clock API
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
`cy.clock` yields a `clock` object with the following methods. You can also access the `clock` object via `this.clock` in a [`cy.then`](https://on.cypress.io/api/then) callback.
|
||||
```javascript
|
||||
cy.clock()
|
||||
```
|
||||
|
||||
## clock.tick(*milliseconds*)
|
||||
## Arguments
|
||||
|
||||
Move the clock the specified number of `milliseconds`. Any timers within the affected range of time will be called.
|
||||
**{% fa fa-angle-right %} now** ***(Date)***
|
||||
|
||||
## clock.restore()
|
||||
A timestamp specifying where the clock should start.
|
||||
|
||||
Restore all overridden native functions. This is automatically called between tests, so should not generally be needed.
|
||||
**{% fa fa-angle-right %} functionNames** ***(Array)***
|
||||
|
||||
# Options
|
||||
Name of native functions that clock should override.
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.clock`.
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
**cy.clock( *options* )**
|
||||
|
||||
**cy.clock( *now*, *options* )**
|
||||
|
||||
**cy.clock( *now*, *functionNames*, *options* )**
|
||||
Pass in an options object to change the default behavior of `cy.clock()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Create a clock and use it to trigger a setInterval
|
||||
`cy.clock()` yields a `clock` object with the following methods.
|
||||
|
||||
**`clock.tick(milliseconds)`**
|
||||
|
||||
Move the clock the specified number of `milliseconds`. Any timers within the affected range of time will be called.
|
||||
|
||||
**`clock.restore()`**
|
||||
|
||||
Restore all overridden native functions. This is automatically called between tests, so should not generally be needed.
|
||||
|
||||
You can also access the `clock` object via `this.clock` in a [`.then()`](https://on.cypress.io/api/then) callback.
|
||||
|
||||
## Timeout
|
||||
|
||||
# Examples
|
||||
|
||||
## Clock
|
||||
|
||||
**Create a clock and use it to trigger a setInterval**
|
||||
|
||||
```javascript
|
||||
// your app code
|
||||
@@ -72,47 +85,17 @@ setInterval(function(){
|
||||
```
|
||||
|
||||
```javascript
|
||||
// test code
|
||||
cy
|
||||
.clock()
|
||||
.visit("/index.html")
|
||||
.tick(1000)
|
||||
.get("#seconds-elapsed")
|
||||
.should("have.text", "1 seconds")
|
||||
.tick(1000)
|
||||
.get("#seconds-elapsed")
|
||||
.should("have.text", "2 seconds")
|
||||
cy.clock()
|
||||
cy.visit('/index.html')
|
||||
cy.tick(1000)
|
||||
cy.get('#seconds-elapsed').should('have.text', '1 seconds')
|
||||
cy.tick(1000)
|
||||
cy.get('#seconds-elapsed').should('have.text', '2 seconds')
|
||||
```
|
||||
|
||||
## Specify the now timestamp
|
||||
**Access the clock object to synchronously move time**
|
||||
|
||||
```javascript
|
||||
// your app code
|
||||
$('#date').text(new Date().toJSON())
|
||||
```
|
||||
|
||||
```javascript
|
||||
// test code
|
||||
const now = new Date(2017, 2, 14).getTime() // March 14, 2017 timestamp
|
||||
|
||||
cy
|
||||
.clock(now)
|
||||
.visit("/index.html")
|
||||
.get("#date")
|
||||
.contains("2017-03-14")
|
||||
```
|
||||
|
||||
## Specify which functions to override
|
||||
|
||||
This will only override `setTimeout` and `clearTimeout` and leave the other time-related functions as they are.
|
||||
|
||||
```javascript
|
||||
cy.clock(null, ["setTimeout", "clearTimeout"])
|
||||
```
|
||||
|
||||
## Access the clock object to synchronously move time
|
||||
|
||||
In most cases, it's easier to [`cy.tick`](https://on.cypress.io/api/tick) to move time, but you can also use `clock` object yielded by `cy.clock`.
|
||||
In most cases, it's easier to [`.tick()`](https://on.cypress.io/api/tick) to move time, but you can also use the `clock` object yielded by `cy.clock()`.
|
||||
|
||||
```javascript
|
||||
cy.clock().then(function (clock) {
|
||||
@@ -120,32 +103,29 @@ cy.clock().then(function (clock) {
|
||||
})
|
||||
```
|
||||
|
||||
You can call `cy.clock` again for this purpose later in a chain if necessary.
|
||||
You can call `.clock()` again for this purpose later in a chain if necessary.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.clock()
|
||||
.get("#foo")
|
||||
.type("Foo")
|
||||
.clock().then(function (clock) {
|
||||
clock.tick(1000)
|
||||
})
|
||||
cy.clock()
|
||||
cy.get('input').type('Jane Lane')
|
||||
cy.clock().then(function (clock) {
|
||||
clock.tick(1000)
|
||||
})
|
||||
```
|
||||
|
||||
The clock object is also available via `this.clock` in any `.then` callback.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.clock()
|
||||
.get("#foo").then(function ($foo) {
|
||||
this.clock.tick(1000)
|
||||
// do something with $foo ...
|
||||
})
|
||||
cy.clock()
|
||||
cy.get('form').then(function ($form) {
|
||||
this.clock.tick(1000)
|
||||
// do something with $form ...
|
||||
})
|
||||
```
|
||||
|
||||
## Access the clock object to restore native functions
|
||||
**Access the clock object to restore native functions**
|
||||
|
||||
In general, it should not be necessary to manually restore the native functions that `cy.clock` overrides, since this is done automatically between tests. But if you need to, the `clock` object yielded has `.restore` method.
|
||||
In general, it should not be necessary to manually restore the native functions that `cy.clock()` overrides, since this is done automatically between tests. But if you need to, the `clock` object yielded has a `.restore` method.
|
||||
|
||||
```javascript
|
||||
cy.clock().then(function (clock) {
|
||||
@@ -156,28 +136,61 @@ cy.clock().then(function (clock) {
|
||||
Or via `this.clock`:
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.clock()
|
||||
.get("#foo").then(function ($foo) {
|
||||
this.clock.restore()
|
||||
// do something with $foo ...
|
||||
})
|
||||
cy.clock()
|
||||
cy.get('.timer').then(function ($timer) {
|
||||
this.clock.restore()
|
||||
// do something with $timer ...
|
||||
})
|
||||
```
|
||||
|
||||
## Example Recipe
|
||||
## Now
|
||||
|
||||
**Specify a now timestamp**
|
||||
|
||||
```javascript
|
||||
// your app code
|
||||
$('#date').text(new Date().toJSON())
|
||||
```
|
||||
|
||||
```javascript
|
||||
const now = new Date(2017, 2, 14).getTime() // March 14, 2017 timestamp
|
||||
|
||||
cy.clock(now)
|
||||
cy.visit('/index.html')
|
||||
cy.get('#date').contains('2017-03-14')
|
||||
```
|
||||
|
||||
## Function Names
|
||||
|
||||
**Specify which functions to override**
|
||||
|
||||
This example below will only override `setTimeout` and `clearTimeout` and leave the other time-related functions as they are.
|
||||
|
||||
```javascript
|
||||
cy.clock(null, ['setTimeout', 'clearTimeout'])
|
||||
```
|
||||
|
||||
{% note info Using cy.clock and cy.tick %}
|
||||
[Check out our example recipe testing spying, stubbing and time](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/spy_stub_clock_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
# Notes
|
||||
|
||||
**iframes not supported**
|
||||
|
||||
Note that this only applies to the `top` window on a web page. It will not override the time functions on any `iframe` embedded on the web page.
|
||||
|
||||
**clock behavior before `.visit()`**
|
||||
|
||||
If you call `cy.clock` before visiting a page with [`cy.visit`](https://on.cypress.io/api/visit), the page's native global functions will be overridden on window load, before any of your app code runs, so even if `setTimeout`, for example, is called on page load, it can still be controlled via [`cy.tick`](https://on.cypress.io/api/tick). This also applies if, during the course of a test, the page under test is reloaded or changed.
|
||||
|
||||
# Command Log
|
||||
|
||||
## Create a clock and tick it 1 second
|
||||
**Create a clock and tick it 1 second**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.clock()
|
||||
.tick(1000)
|
||||
cy.clock()
|
||||
cy.tick(1000)
|
||||
```
|
||||
|
||||
The command above will display in the command log as:
|
||||
@@ -188,7 +201,7 @@ When clicking on the `clock` command within the command log, the console outputs
|
||||
|
||||
<img width="1059" alt="screen shot of console output" src="https://cloud.githubusercontent.com/assets/1157043/22437920/0786f9d8-e6f8-11e6-9e77-926b15aa8dae.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [Guide: Stubs, Spies and Clocks ](https://on.cypress.io/guides/stubs-spies-clocks)
|
||||
- [Recipe: Controlling Behavior with Spies, Stubs, and Clocks](https://github.com/cypress-io/cypress-example-recipes#controlling-behavior-with-spies-stubs-and-clocks)
|
||||
|
||||
@@ -4,42 +4,71 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the first DOM element that matches the selector whether it be itself or one of it's ancestors.
|
||||
Get the first DOM element that matches the selector (whether it be itself or one of it's ancestors).
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.filter` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.closest( *selector* )](#selector-usage)
|
||||
```javascript
|
||||
.closest(selector)
|
||||
.closest(selector, options)
|
||||
```
|
||||
|
||||
For each DOM element in the set, get the first DOM element that matches the selector by testing the DOM element itself and traversing up through its ancestors in the DOM tree.
|
||||
## Usage
|
||||
|
||||
# Options
|
||||
`.closest()` requires being chained off another cy command that *yields* a DOM element.
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.closest`.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
**cy.closest( *selector*, *options* )**
|
||||
```javascript
|
||||
cy.get('td').closest('.filled') // Yield closest el with class '.filled'
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.closest('.active') // Errors, cannot be chained off 'cy'
|
||||
cy.url().closest() // Errors, 'url' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
A selector used to filter matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.closest()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
|
||||
# Selector Usage
|
||||
## Yields
|
||||
|
||||
## Find the closest element of the current subject with the class `nav`
|
||||
`.closest()` yields the new DOM elements found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.closest()` will continue to look for the closest element for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Closest
|
||||
|
||||
**Find the closest element of the current subject with the class `nav`**
|
||||
|
||||
```javascript
|
||||
cy.get("li.active").closest(".nav")
|
||||
cy.get('li.active').closest('.nav')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Find the closest element of the current subject with the class `nav`
|
||||
**Find the closest element of the current subject with the class `nav`**
|
||||
|
||||
```javascript
|
||||
cy.get("li.active").closest(".nav")
|
||||
cy.get('li.active').closest('.nav')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -50,8 +79,12 @@ When clicking on the `closest` command within the command log, the console outpu
|
||||
|
||||
<img width="478" alt="screen shot 2015-11-27 at 2 07 46 pm" src="https://cloud.githubusercontent.com/assets/1271364/11447201/535515c4-9510-11e5-9cf5-088bf21f34ac.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [parent](https://on.cypress.io/api/parent)
|
||||
- [parents](https://on.cypress.io/api/parents)
|
||||
- [next](https://on.cypress.io/api/next)
|
||||
- [parentsUntil](https://on.cypress.io/api/parentsUntil)
|
||||
- [prev](https://on.cypress.io/api/prev)
|
||||
- [prevAll](https://on.cypress.io/api/prevAll)
|
||||
- [prevUntil](https://on.cypress.io/api/prevUntil)
|
||||
- [first](https://on.cypress.io/api/first)
|
||||
|
||||
@@ -4,51 +4,66 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the DOM element containing the text. DOM elements can contain *more* than the desired text and still match. Additionally, Cypress will prefer some DOM elements over the deepest element found.
|
||||
Get the DOM element containing the text. DOM elements can contain *more* than the desired text and still match. Additionally, Cypress will [prefer some DOM elements](#notes) over the deepest element found.
|
||||
|
||||
**Preference order:**
|
||||
# Syntax
|
||||
|
||||
- `input[type='submit']`
|
||||
- `button`
|
||||
- `a`
|
||||
- `label`
|
||||
```javascript
|
||||
cy.contains(content)
|
||||
cy.contains(selector, content)
|
||||
cy.contains(selector, content, options)
|
||||
```
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the deepest DOM element containing the text |
|
||||
| **Timeout** | `cy.contains` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
## Usage
|
||||
|
||||
# [cy.contains( *text* )](#text-usage)
|
||||
`.contains()` can be chained off of `cy` to find content within the entire document or chained off another cy command that *yields* a DOM element - limiting it's search of content to within yielded element.
|
||||
|
||||
Get the deepest DOM element containing the text.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# [cy.contains( *number* )](#number-usage)
|
||||
```javascript
|
||||
cy.get('.nav').contains('About') // Yields el in .nav containing 'About'
|
||||
cy.contains('Hello') // Yields first el in document containing 'Hello'
|
||||
```
|
||||
|
||||
Get the deepest DOM element containing the number.
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
# [cy.contains( *regexp* )](#regular-expression-usage)
|
||||
```javascript
|
||||
cy.title().contains('My App') // Errors, 'title' does not yield DOM element
|
||||
cy.getCookies().contains('_key') // Errors, 'getCookies' does not yield DOM element
|
||||
```
|
||||
|
||||
Get the deepest DOM element containing the text matching the regular expression.
|
||||
## Arguments
|
||||
|
||||
# [cy.contains( *selector*, *text* )](#selector-and-text-usage)
|
||||
**{% fa fa-angle-right %} content** ***(String, Number, RegExp)***
|
||||
|
||||
Specify a selector to filter DOM elements containing the text. Cypress will **ignore** it's default preference for the specified selector. Using a selector allows you to return more *shallow* elements in the tree which contain the specific text.
|
||||
Get the deepest DOM element containing the content.
|
||||
|
||||
# Options
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
Specify a selector to filter DOM elements containing the text. Cypress will *ignore* it's [default preference order](#notes) for the specified selector. Using a selector allows you to return more *shallow* elements in the tree which contain the specific text.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.contains`.
|
||||
|
||||
**cy.contains( *text*, *options* )**
|
||||
**cy.contains( *selector*, *text*, *options* )**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry finding an element
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry finding an element containing the content
|
||||
|
||||
# Text Usage
|
||||
## Yields
|
||||
|
||||
## Find the first element containing some text
|
||||
`cy.contains()` yields the *first*, *deepest* DOM element containing the text.
|
||||
|
||||
## Timeout
|
||||
|
||||
`cy.contains()` will try to find the content within the DOM for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## String Content
|
||||
|
||||
**Find the first element containing some text**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -59,11 +74,13 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
// returns <li>apples</li>
|
||||
cy.contains("apples")
|
||||
// yields <li>apples</li>
|
||||
cy.contains('apples')
|
||||
```
|
||||
|
||||
## Find the input[type='submit'] by value
|
||||
**Find the input[type='submit'] by value**
|
||||
|
||||
Get the form element and search in its descendants for the content "submit the form!"
|
||||
|
||||
```html
|
||||
<div id="main">
|
||||
@@ -82,14 +99,13 @@ cy.contains("apples")
|
||||
```
|
||||
|
||||
```javascript
|
||||
// get the form element
|
||||
// search inside its descendants for the content 'submit the form!'
|
||||
// find the input[type='submit'] element
|
||||
// click it
|
||||
cy.get("form").contains("submit the form!").click()
|
||||
// yields input[type='submit'] element then clicks it
|
||||
cy.get('form').contains('submit the form!').click()
|
||||
```
|
||||
|
||||
## Favor of `button` over other deeper elements
|
||||
**Favor of `button` over other deeper elements**
|
||||
|
||||
Even though the `<span>` is the deepest element that contains "Search", Cypress will yield `button` elements over spans.
|
||||
|
||||
```html
|
||||
<form>
|
||||
@@ -101,21 +117,16 @@ cy.get("form").contains("submit the form!").click()
|
||||
```
|
||||
|
||||
```javascript
|
||||
// even though the <span> is the deepest element that contains: "Search"
|
||||
// Cypress will automatically favor button elements higher in the chain
|
||||
|
||||
// in this case the <button> is returned which is why we can now drill
|
||||
// into its children
|
||||
cy.contains("Search").children("i").should("have.class", "fa-search")
|
||||
// yields <button>
|
||||
cy.contains('Search').children('i').should('have.class', 'fa-search')
|
||||
```
|
||||
|
||||
## Favor of `a` over other deeper elements
|
||||
**Favor of `a` over other deeper elements**
|
||||
|
||||
Even though the `<span>` is the deepest element that contains "Sign Out", Cypress will yield anchor elements over spans.
|
||||
|
||||
```html
|
||||
<nav>
|
||||
<a href="/dashboard">
|
||||
<span>Dashboard</span>
|
||||
</a>
|
||||
<a href="/users">
|
||||
<span>Users</span>
|
||||
</a>
|
||||
@@ -126,14 +137,15 @@ cy.contains("Search").children("i").should("have.class", "fa-search")
|
||||
```
|
||||
|
||||
```javascript
|
||||
// even though the <span> is the deepest element that contains: "Sign Out"
|
||||
// Cypress will automatically favor anchor elements higher in the chain
|
||||
|
||||
// in this case we can assert on the anchors properties
|
||||
cy.get("nav").contains("Sign Out").should("have.attr", "href", "/signout")
|
||||
// yields <a>
|
||||
cy.get('nav').contains('Sign Out').should('have.attr', 'href', '/signout')
|
||||
```
|
||||
|
||||
## Favor of `label` over other deeper elements
|
||||
**Favor of `label` over other deeper elements**
|
||||
|
||||
Even though the `<span>` is the deepest element that contains "Age", Cypress will yield `label` elements over `span`.
|
||||
|
||||
Additionally we don't need to look for content "Age:" omit as long as the element at least contains the text "Age", it will be yielded.
|
||||
|
||||
```html
|
||||
<form>
|
||||
@@ -149,16 +161,11 @@ cy.get("nav").contains("Sign Out").should("have.attr", "href", "/signout")
|
||||
```
|
||||
|
||||
```javascript
|
||||
// even though the <span> is the deepest element that contains: "Age"
|
||||
// Cypress will favor label elements higher in the chain
|
||||
|
||||
// additionally we can omit the colon as long as the element
|
||||
// at least contains the text 'Age'
|
||||
|
||||
cy.contains("Age").find("input").type("29")
|
||||
// yields label
|
||||
cy.contains('Age').find('input').type('29')
|
||||
```
|
||||
|
||||
## Only the *first* matched element will be returned
|
||||
**Only the *first* matched element will be returned**
|
||||
|
||||
```html
|
||||
<ul id="header">
|
||||
@@ -167,28 +174,31 @@ cy.contains("Age").find("input").type("29")
|
||||
<div id="main">
|
||||
<span>These users have 10 connections with Jane Lane</span>
|
||||
<ul>
|
||||
<li>User 1</li>
|
||||
<li>User 2</li>
|
||||
<li>User 3</li>
|
||||
<li>Jamal</li>
|
||||
<li>Patricia</li>
|
||||
</ul>
|
||||
</div>
|
||||
```
|
||||
|
||||
The below example will return the `<li>` in the `#header` since that is the *first* element that contains the text "Jane Lane".
|
||||
|
||||
```javascript
|
||||
// this will return the <li> in the #header since that is the first
|
||||
// element that contains the text "Jane Lane"
|
||||
cy.contains("Jane Lane")
|
||||
|
||||
// if you want to select the <span> inside of #main instead
|
||||
// you need to scope the contains first
|
||||
|
||||
//now the <span> is returned
|
||||
cy.get("#main").contains("Jane Lane")
|
||||
// yields #header li
|
||||
cy.contains('Jane Lane')
|
||||
```
|
||||
|
||||
# Number Usage
|
||||
If you wanted to select the `<span>` instead, you could narrow the elements yielded before the `.contains()`.
|
||||
|
||||
## Find the first element containing some number
|
||||
```javascript
|
||||
// yields <span>
|
||||
cy.get('#main').contains('Jane Lane')
|
||||
```
|
||||
|
||||
## Number Content
|
||||
|
||||
**Find the first element containing some number**
|
||||
|
||||
Even though the `<span>` is the deepest element that contains a "4", Cypress will automatically yield `button` elements higher in the chain
|
||||
|
||||
```html
|
||||
<button class="btn btn-primary" type="button">
|
||||
@@ -197,16 +207,13 @@ cy.get("#main").contains("Jane Lane")
|
||||
```
|
||||
|
||||
```javascript
|
||||
// even though the <span> is the deepest element that contains: 4
|
||||
// Cypress will automatically favor button elements higher in the chain
|
||||
|
||||
// in this case the <button> is returned
|
||||
// yields <button>
|
||||
cy.contains(4)
|
||||
```
|
||||
|
||||
# Regular Expression Usage
|
||||
## Regular Expression Content
|
||||
|
||||
## Find the first element with text matching the regular expression
|
||||
**Find the first element with text matching the regular expression**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -217,13 +224,19 @@ cy.contains(4)
|
||||
```
|
||||
|
||||
```javascript
|
||||
// <li>bananas</li> is returned
|
||||
// yields <li>bananas</li>
|
||||
cy.contains(/^b\w+/)
|
||||
```
|
||||
|
||||
# Selector and Text Usage
|
||||
## Selector
|
||||
|
||||
## Specify a selector to return a specific element
|
||||
**Specify a selector to return a specific element**
|
||||
|
||||
Technically the `<html>`, `<body>`, `<ul>`, and first `<li>` in the example below all contain "apples".
|
||||
|
||||
Normally Cypress would return the first `<li>` since that is the *deepest* element that contains: "apples"
|
||||
|
||||
To override the element that is yielded, we can pass `ul` as the selector.
|
||||
|
||||
```html
|
||||
<html>
|
||||
@@ -238,95 +251,92 @@ cy.contains(/^b\w+/)
|
||||
```
|
||||
|
||||
```javascript
|
||||
// technically the <html>, <body>, <ul>, and first <li> all contain "apples"
|
||||
|
||||
// normally Cypress would return the first <li> since that is the deepest
|
||||
// element that contains: "apples"
|
||||
|
||||
// to override this behavior, pass a 'ul' selector
|
||||
// this returns the ul element since it also contains the text
|
||||
|
||||
// returns <ul>...</ul>
|
||||
cy.contains("ul", "apples")
|
||||
// yields <ul>...</ul>
|
||||
cy.contains('ul', 'apples')
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
## Dual command can be either parent or child
|
||||
**Element preference order**
|
||||
|
||||
- `input[type='submit']`
|
||||
- `button`
|
||||
- `a`
|
||||
- `label`
|
||||
|
||||
**Dual command can be either parent or child**
|
||||
|
||||
`cy.contains` is a dual command. This means it can act as both a `parent` and a `child` command. Read more about [issuing commands](https://on.cypress.io/guides/issuing-commands) if this is unfamiliar.
|
||||
|
||||
Because it is a dual command it can either *begin* a chain of commands or work off of an *existing* subject.
|
||||
|
||||
**Start a chain of commands**
|
||||
***Start a chain of commands***
|
||||
|
||||
Search for the content within the `document`.
|
||||
|
||||
```javascript
|
||||
// search from the root scope (default: document)
|
||||
cy.contains("some content")
|
||||
cy.contains('some content')
|
||||
```
|
||||
|
||||
**Find content within an existing scope**
|
||||
***Find content within an existing scope***
|
||||
|
||||
Search within an existing subject for the content. `.contains()` will be scoped to the `<aside>` element and will only search it's DOM descendants for the content.
|
||||
|
||||
```javascript
|
||||
// search within an existing subject for the content
|
||||
// contains is now scoped to the <aside> element and will
|
||||
// only search its DOM descendants for the content
|
||||
cy.get("#main").find("aside").contains("Add a user")
|
||||
cy.get('#main').find('aside').contains('Add a user')
|
||||
```
|
||||
|
||||
**Be wary of chaining multiple contains**
|
||||
***Be wary of chaining multiple contains***
|
||||
|
||||
Let's imagine a scenario where you click button to delete a user and a dialog appears asking you to confirm this deletion.
|
||||
|
||||
The following will not work:
|
||||
|
||||
```javascript
|
||||
// let's imagine a scenario where you click a user's delete button
|
||||
// and a dialog appears asking you to confirm this deletion.
|
||||
|
||||
// the following will not work:
|
||||
cy
|
||||
.contains("Delete User").click()
|
||||
|
||||
// because this is chained off of the existing button subject
|
||||
// Cypress will look inside of the existing button subject
|
||||
// for the new content
|
||||
|
||||
// in other words Cypress will look inside of the element
|
||||
// containing "Delete User" for the content: "Yes I'm sure!"
|
||||
.contains("Yes, I'm sure!").click()
|
||||
|
||||
.contains('Delete User').click()
|
||||
.contains('Yes, Delete!').click()
|
||||
```
|
||||
|
||||
**End previous chains to get back to the root scope**
|
||||
Because the second `.contains()` is chained off of the existing button subject, Cypress will look inside of the existing button subject for the new content.
|
||||
|
||||
In other words, Cypress will look inside of the button containing "Delete User" for the content: "Yes, Delete!"
|
||||
|
||||
***End previous chains to get back to the root scope***
|
||||
|
||||
If you explicitly [`.end()`](https://on.cypress.io/api/end) the previous chain, Cypress within the `document` for the content.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
// explicitly .end() the previous chain
|
||||
.contains("Delete User").click().end()
|
||||
|
||||
// Cypress will now search the root scope
|
||||
// for this content (default: document)
|
||||
.contains("Yes, I'm sure!").click()
|
||||
.contains('Delete User').click().end()
|
||||
.contains('Yes, Delete!').click()
|
||||
```
|
||||
|
||||
```javascript
|
||||
// alternatively just call cy again which
|
||||
// automatically creates a new chain from the root scope
|
||||
cy.contains("Delete User").click()
|
||||
cy.contains("Yes I'm sure!").click()
|
||||
```
|
||||
Alternatively, you could call `cy` again which automatically creates a new chain from the `document`.
|
||||
|
||||
```javascript
|
||||
cy.contains('Delete User').click()
|
||||
cy.contains('Yes, Delete!').click()
|
||||
```
|
||||
|
||||
You could also chain the second contains off of a parent command (such as [`.get()`](https://on.cypress.io/api/get). This automatically changes the subject to `#dialog` which contains the content we're looking for.
|
||||
|
||||
```javascript
|
||||
// you can also do this
|
||||
cy
|
||||
.contains("Delete User").click()
|
||||
|
||||
// by using the parent command .get() we automatically
|
||||
// abort previous chains and change the scope to #dialog
|
||||
// which contains the content we're looking for
|
||||
.get("#dialog").contains("Yes I'm sure!").click()
|
||||
.contains('Delete User').click()
|
||||
.get('#dialog').contains('Yes, Delete!').click()
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Element contains text "New User"
|
||||
**Element contains text "New User"**
|
||||
|
||||
```javascript
|
||||
cy.get('h1').contains('New User')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
|
||||
<img width="536" alt="screen shot 2015-11-27 at 1 43 22 pm" src="https://cloud.githubusercontent.com/assets/1271364/11446973/009ac32c-950d-11e5-9eaa-09f8b8ddf086.png">
|
||||
|
||||
@@ -334,7 +344,7 @@ When clicking on the `contains` command within the command log, the console outp
|
||||
|
||||
<img width="477" alt="screen shot 2015-11-27 at 1 43 50 pm" src="https://cloud.githubusercontent.com/assets/1271364/11446977/04b31be4-950d-11e5-811e-4fd83d364d00.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [get](https://on.cypress.io/api/get)
|
||||
- [within](https://on.cypress.io/api/within)
|
||||
|
||||
@@ -4,48 +4,74 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Double-click on the DOM element in the previous command.
|
||||
Double-click a DOM element.
|
||||
|
||||
**The following events are fired during dblclick:** `dblclick`
|
||||
# Syntax
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.dblclick` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
```javascript
|
||||
.dblclick()
|
||||
.dblclick(options)
|
||||
```
|
||||
|
||||
# [cy.dblclick()](#usage)
|
||||
## Usage
|
||||
|
||||
Double-click the current subject.
|
||||
`.dblclick()` requires being chained off another cy command that *yields* a DOM element.
|
||||
|
||||
# Options
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.dblclick`.
|
||||
```javascript
|
||||
cy.get('button').dblclick() // Double clicks on button
|
||||
cy.focused().dblclick() // Double clicks on el with focus
|
||||
cy.contains('Welcome').dblclick() // Double clicks on first el containing 'Welcome'
|
||||
```
|
||||
|
||||
**cy.dblclick(*options* )**
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.click('button') // Errors, cannot be chained off 'cy'
|
||||
cy.window().click() // Errors, 'window' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
|
||||
Pass in an options object to change the default behavior of `.dblclick()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
|
||||
## Double click an anchor link
|
||||
## Yields
|
||||
|
||||
`.dblclick()` yields the DOM subject chained from the previous command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.dblclick()` will wait for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Double Click
|
||||
|
||||
**Double click an anchor link**
|
||||
|
||||
```html
|
||||
<a href='#nav1'>Menu</a>
|
||||
<a href="#nav1">Menu</a>
|
||||
```
|
||||
|
||||
```javascript
|
||||
// returns the <a> for further chaining
|
||||
cy.get("#nav1").dblclick()
|
||||
cy.get('#nav1').dblclick() // yields the <a>
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Double click on a calendar schedule
|
||||
**Double click on a calendar schedule**
|
||||
|
||||
```javascript
|
||||
cy.get("[data-schedule-id='4529114']:first").dblclick()
|
||||
cy.get('[data-schedule-id="4529114"]:first').dblclick()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -56,6 +82,6 @@ When clicking on `dblclick` within the command log, the console outputs the foll
|
||||
|
||||
<img width="836" alt="screen shot 2015-11-29 at 1 12 26 pm" src="https://cloud.githubusercontent.com/assets/1271364/11459015/0755e216-969b-11e5-9f7e-ed04245d75ef.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [click](https://on.cypress.io/api/click)
|
||||
|
||||
@@ -4,39 +4,72 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
`cy.debug` sets a `debugger` and logs the subject from the previous command.
|
||||
Set a `debugger` and log what the previous command yields.
|
||||
|
||||
Make sure you have your Developer Tools open for `cy.debug` to hit the breakpoint.
|
||||
{% note warning %}
|
||||
You need to have your Developer Tools open for `.debug()` to hit the breakpoint.
|
||||
{% endnote %}
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the subject from the previous command for further chaining. |
|
||||
| **Timeout** | *cannot timeout* |
|
||||
# Syntax
|
||||
|
||||
# [cy.debug()](#usage)
|
||||
```javascript
|
||||
.debug()
|
||||
.debug(options)
|
||||
```
|
||||
|
||||
Debug the previous command.
|
||||
## Usage
|
||||
|
||||
# Options
|
||||
`.debug()` can be chained off of `cy` or any cy command.
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.debug`.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
**cy.debug(*options* )**
|
||||
```javascript
|
||||
cy.debug().getCookie('app') // Pause to debug at beginning of commands
|
||||
cy.get('nav').debug() // Debug the `get` commands yield
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.debug()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Log out the current subject for debugging
|
||||
`.debug()` yields the previous command's yield.
|
||||
|
||||
## Timeout
|
||||
|
||||
# Examples
|
||||
|
||||
## Debug
|
||||
|
||||
**Pause with debugger after `get()`**
|
||||
|
||||
```javascript
|
||||
// Cypress will log out the current subject and other
|
||||
// useful debugging information to your console
|
||||
cy.get("a").debug().should("have.attr", "href")
|
||||
cy.get('a').debug().should('have.attr', 'href')
|
||||
```
|
||||
|
||||
# Related
|
||||
# Command Log
|
||||
|
||||
**Log out the current subject for debugging**
|
||||
|
||||
```javascript
|
||||
cy.get(".ls-btn").click({ force: true }).debug()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
|
||||
<img width="466" alt="screen shot 2017-05-24 at 4 10 23 pm" src="https://cloud.githubusercontent.com/assets/1271364/26423391/896b858e-409b-11e7-91ce-14c5bf38ab11.png">
|
||||
|
||||
When clicking on the `debug` command within the command log, the console outputs the following:
|
||||
|
||||
<img width="572" alt="screen shot 2017-05-24 at 4 10 08 pm" src="https://cloud.githubusercontent.com/assets/1271364/26423392/89725486-409b-11e7-94d5-aebdffe16abf.png">
|
||||
|
||||
# See also
|
||||
|
||||
- [pause](https://on.cypress.io/api/pause)
|
||||
|
||||
@@ -4,30 +4,48 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the document and work with its properties or methods.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the `window.document` object |
|
||||
| **Timeout** | `cy.document` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
|
||||
# [cy.document()](#usage)
|
||||
|
||||
Get the document.
|
||||
|
||||
# Options
|
||||
# Syntax
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.document`.
|
||||
```javascript
|
||||
.document()
|
||||
.document(options)
|
||||
```
|
||||
|
||||
**cy.document(*options* )**
|
||||
## Usage
|
||||
|
||||
`.document()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.document()
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.document()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Get document and do some work
|
||||
`.as()` yields the `window.document` object.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.document()` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Document
|
||||
|
||||
**Get document and do some work**
|
||||
|
||||
```javascript
|
||||
cy.document().then(function(document) {
|
||||
@@ -35,21 +53,21 @@ cy.document().then(function(document) {
|
||||
});
|
||||
```
|
||||
|
||||
## Make an assertion about the document
|
||||
**Make an assertion about the document**
|
||||
|
||||
```javascript
|
||||
cy.document().its("contentType").should("eq", "text/html")
|
||||
cy.document().its('contentType').should('eq', 'text/html')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Get the document
|
||||
**Get the document**
|
||||
|
||||
```javascript
|
||||
cy.document()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
The command above will display in the command log as:
|
||||
|
||||
<img width="588" alt="screen shot 2015-11-29 at 2 00 09 pm" src="https://cloud.githubusercontent.com/assets/1271364/11459311/aab8fe88-96a1-11e5-9b72-b0501204030d.png">
|
||||
|
||||
@@ -57,6 +75,6 @@ When clicking on `document` within the command log, the console outputs the foll
|
||||
|
||||
<img width="491" alt="screen shot 2015-11-29 at 2 00 22 pm" src="https://cloud.githubusercontent.com/assets/1271364/11459314/ad27d7e8-96a1-11e5-8d1c-9c4ede6c54aa.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [window](https://on.cypress.io/api/window)
|
||||
|
||||
@@ -4,33 +4,57 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
The `cy.each()` will iterate through an array like structure (arrays and objects with a `length` property).
|
||||
Iterate through an array like structure (arrays or objects with a `length` property).
|
||||
|
||||
Each time the callback function runs, it is invoked with three arguments: `value`, `index`, and `collection`.
|
||||
Each time the callback function runs, it is invoked with three arguments:
|
||||
|
||||
If your callback function returns a `Promise` it will be awaited before iterating over the next element in the collection.
|
||||
- `value`
|
||||
- `index`
|
||||
- `collection`
|
||||
|
||||
You can stop the loop early by returning `false` in the callback function.
|
||||
# Syntax
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the original array subject given to `cy.each()` |
|
||||
| **Timeout** | `cy.each` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
```javascript
|
||||
.each(function(value, index, collection) {})
|
||||
```
|
||||
|
||||
# [cy.each( *function* )](#usage)
|
||||
## Usage
|
||||
|
||||
Iterate over an array-like structure.
|
||||
`.each()` requires being chained off another cy command that *yields* an array like structure (arrays or objects with a `length` property).
|
||||
|
||||
# Usage
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
## Iterate over an array of DOM elements
|
||||
```javascript
|
||||
cy.get('ul>li').each(function(){...}) // Iterate through each 'li'
|
||||
cy.getCookies().each(function(){...}) // Iterate through each cookie
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
|
||||
cy.each(function(){...}) // Errors, cannot be chained off 'cy'
|
||||
cy.location().each(function(){...}) // Errors, 'location' doesn't yield an array
|
||||
```
|
||||
|
||||
## Yields
|
||||
|
||||
`.each()` yields the original array.
|
||||
|
||||
## Timeout
|
||||
|
||||
# Examples
|
||||
|
||||
## DOM Elements
|
||||
|
||||
**Iterate over an array of DOM elements**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("ul>li")
|
||||
.get('ul>li')
|
||||
.each(function($el, index, $list){
|
||||
// $el is wrapped jquery element
|
||||
if ($el.someMethod() === "something") {
|
||||
// $el is a wrapped jQuery element
|
||||
if ($el.someMethod() === 'something') {
|
||||
// wrap this element so we can
|
||||
// use cypress commands on it
|
||||
cy.wrap($el).click()
|
||||
@@ -40,14 +64,31 @@ cy
|
||||
})
|
||||
```
|
||||
|
||||
## Promises are awaited
|
||||
**The original array is always yielded**
|
||||
|
||||
No matter what is returned in the callback function, `.each()` will always yield the original array.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get('li').should('have.length', 3)
|
||||
.each(function($li, index, $lis){
|
||||
return 'something else'
|
||||
})
|
||||
.then(function($lis){
|
||||
expect($lis).to.have.length(3) // true
|
||||
})
|
||||
```
|
||||
|
||||
## Promises
|
||||
|
||||
**Promises are awaited**
|
||||
|
||||
If your callback function returns a `Promise` it will be awaited before iterating over the next element in the collection.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.wrap([1,2,3])
|
||||
.each(function(num, index, array){
|
||||
// promises returned are automatically
|
||||
// awaited on before calling the next item
|
||||
return new Cypress.Promise(function(resolve){
|
||||
setTimeout(function(){
|
||||
resolve()
|
||||
@@ -56,29 +97,13 @@ cy
|
||||
})
|
||||
```
|
||||
|
||||
## The original subject is always returned
|
||||
# Notes
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("li").should("have.length", 3)
|
||||
.each(function($li, index, $lis){
|
||||
// no matter what we return here
|
||||
// the next subject will still
|
||||
// be the collection of <li>
|
||||
return "something else"
|
||||
})
|
||||
.then(function($lis){
|
||||
expect($lis).to.have.length(3) // true
|
||||
})
|
||||
```
|
||||
**Stop `each` prematurely**
|
||||
|
||||
# Errors
|
||||
You can stop the `.each()` loop early by returning `false` in the callback function.
|
||||
|
||||
## cy.each() can only operate on an array like subject.
|
||||
|
||||
This error occurs when the subject passed to `cy.each()` does not have a `length` property. Ensure the subject passed to `cy.each()` is an array-like structure.
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [spread](https://on.cypress.io/api/spread)
|
||||
- [then](https://on.cypress.io/api/then)
|
||||
|
||||
@@ -4,44 +4,61 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Ends the Cypress command chain and returns `null`. This is equivalent to the jQuery `end()` method.
|
||||
End a chain of commands.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | `null` |
|
||||
| **Timeout** | cannot timeout |
|
||||
|
||||
# [cy.end()](#usage)
|
||||
|
||||
End the command chain.
|
||||
|
||||
# Usage
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
// cy.end is useful when you want to end a chain of commands
|
||||
// and force Cypress to re-query from the root element
|
||||
cy
|
||||
.contains("User: Cheryl").click().end() // ends the current chain and returns null
|
||||
.end()
|
||||
```
|
||||
|
||||
// queries the entire document again
|
||||
.contains("User: Charles").click()
|
||||
## Usage
|
||||
|
||||
`.end()` should be chained off another cy command.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.contains('ul').end() // Yield 'null' instead of 'ul' element
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.end() // Does not make sense to chain off 'cy'
|
||||
```
|
||||
|
||||
## Yields
|
||||
|
||||
`.end()` yields `null`.
|
||||
|
||||
|
||||
# Examples
|
||||
|
||||
`.end()` is useful when you want to end a chain of commands and force the next command to not receive what was yielded in the previous command.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.contains('User: Cheryl').click().end() // yield null
|
||||
.contains('User: Charles').click() // contains looks for content in document now
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## `end` does *not* log in the command log
|
||||
**`end` does *not* log in the command log**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.contains(".modal-title", "Select Folder Type").end()
|
||||
.contains("li", "Maintenance").should("have.class", "active")
|
||||
.contains('.modal-title', 'Select Folder Type').end()
|
||||
.contains('li', 'Maintenance').should('have.class', 'active')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
|
||||

|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [root](https://on.cypress.io/api/root)
|
||||
- [within](https://on.cypress.io/api/within)
|
||||
|
||||
@@ -4,36 +4,68 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get a DOM element in an array of elements at the specific index.
|
||||
Get the DOM element at a specific index in an array of elements.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.eq` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.eq( *index* )](#index-usage)
|
||||
```javascript
|
||||
.eq(index)
|
||||
.eq(indexFromEnd)
|
||||
.eq(index, options)
|
||||
.eq(indexFromEnd, options)
|
||||
```
|
||||
|
||||
Reduce the set of matched DOM elements to the one at the specified index.
|
||||
## Usage
|
||||
|
||||
# [cy.eq( *indexFromEnd* )](#index-from-end-usage)
|
||||
`.eq()` requires being chained off another cy command that *yields* a DOM element or set of DOM elements.
|
||||
|
||||
Providing a negative number indicates a position starting from the end of the set, rather than the beginning.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# Options
|
||||
```javascript
|
||||
cy.get('tbody>tr').eq(0) // Yield first 'tr' in 'tbody'
|
||||
cy.get('ul>li').eq('4') // Yield fifth 'li' in 'ul'
|
||||
```
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.eq`.
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
**cy.eq( *index*, *options* )**
|
||||
**cy.eq( *indexFromEnd*, *options* )**
|
||||
```javascript
|
||||
cy.eq(0) // Errors, cannot be chained off 'cy'
|
||||
cy.getCookies().eq('4') // Errors, 'getCookies' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} index** ***(Number)***
|
||||
|
||||
A number indicating the index to find the element at within an array of elements.
|
||||
|
||||
**{% fa fa-angle-right %} indexFromEnd** ***(Number)***
|
||||
|
||||
A negative number indicating the index position from the end of the index to find the element at within an array of elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.eq()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
|
||||
# Index Usage
|
||||
## Yields
|
||||
|
||||
## Find the 2nd element within the elements
|
||||
`.eq()` yields the new DOM elements found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.eq()` will continue to look for the element at the specified index for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
|
||||
# Examples
|
||||
|
||||
## Index
|
||||
|
||||
**Find the 2nd element within the elements**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -46,12 +78,12 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy.get("li").eq(1).should("contain", "siamese") // true
|
||||
cy.get('li').eq(1).should('contain', 'siamese') // true
|
||||
```
|
||||
|
||||
# Index Form End Usage
|
||||
## Index Form End
|
||||
|
||||
## Find the 2nd from the last element within the elements
|
||||
**Find the 2nd from the last element within the elements**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -64,15 +96,15 @@ cy.get("li").eq(1).should("contain", "siamese") // true
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy.get("li").eq(-2).should("contain", "sphynx") // true
|
||||
cy.get('li').eq(-2).should('contain', 'sphynx') // true
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Find the 4th `li` in the navigation
|
||||
**Find the 4th `li` in the navigation**
|
||||
|
||||
```javascript
|
||||
cy.get(".left-nav.nav").find(">li").eq(3)
|
||||
cy.get('.left-nav.nav').find('>li').eq(3)
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -83,7 +115,9 @@ When clicking on the `eq` command within the command log, the console outputs th
|
||||
|
||||
<img width="569" alt="screen shot 2015-11-27 at 2 12 03 pm" src="https://cloud.githubusercontent.com/assets/1271364/11447234/e594ce52-9510-11e5-8794-712a7dbeae55.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [first](https://on.cypress.io/api/first)
|
||||
- [last](https://on.cypress.io/api/last)
|
||||
- [next](https://on.cypress.io/api/next)
|
||||
- [prev](https://on.cypress.io/api/prev)
|
||||
|
||||
@@ -4,47 +4,68 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Allows you to execute a system command. The system command can be anything you would normally run on the command line, such as `npm run build`, `rake db:seed`, etc.
|
||||
|
||||
`cy.exec` provides an escape hatch for running arbitrary system commands, so you can take actions necessary for your test, but outside the scope of Cypress. This is great for running build scripts, seeding your test database, starting or killing processes, etc.
|
||||
|
||||
`cy.exec` does not support commands that don't exit, such as `rails server`, a task that runs a watch, or any process that needs to be manually interrupted to stop. A command must exit within the timeout or Cypress will kill the command's process and fail the current test.
|
||||
|
||||
We don't recommend executing commands that take a long time to exit. Cypress will not continue running any other commands until `cy.exec` has finished, so a long-running command will drastically slow down your test cycle.
|
||||
|
||||
The current working directory is set to the project root (the directory that contains cypress.json).
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | an object with the exit `code`, the `stdout`, and the `stderr` |
|
||||
| **Timeout** | `cy.exec` will allow the command to execute for the duration of the [`execTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
|
||||
# [cy.exec( *command* )](#command-usage)
|
||||
|
||||
Execute a system command.
|
||||
|
||||
# Options
|
||||
# Syntax
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.exec`.
|
||||
```javascript
|
||||
cy.exec(command)
|
||||
cy.exec(command, options)
|
||||
```
|
||||
|
||||
**cy.exec( *command*, *options* )**
|
||||
## Usage
|
||||
|
||||
`.exec()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.exec('npm run build')
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} command** ***(String)***
|
||||
|
||||
The system command to be executed from the project root (the directory that contains `cypress.json`).
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.exec()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`failOnNonZeroExit` | `true` | whether to fail if the command exits with a non-zero code
|
||||
`env` | `{}` | Object of environment variables to set before the command executes (e.g. `{ USERNAME: 'johndoe' }`). Will be merged with existing system environment variables
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`execTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to allow the command to execute
|
||||
`failOnNonZeroExit` | `true` | Fail if the command exits with a non-zero code
|
||||
`env` | `{}` | Object of environment variables to set before the command executes (e.g. { USERNAME: 'johndoe' }). Will be merged with existing system environment variables
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Run a build command
|
||||
`.exec()` yields an object with the exit `code`, `stdout`, and `stderr`.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.exec()` will allow the command to execute for the duration of the [`execTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Prepping data
|
||||
|
||||
`cy.exec` provides an escape hatch for running arbitrary system commands, so you can take actions necessary for your test, but outside the scope of Cypress. This is great for:
|
||||
|
||||
- Running build scripts
|
||||
- Seeding your test database
|
||||
- Starting processes
|
||||
- Killing processes
|
||||
|
||||
**Run a build command**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.exec("npm run build")
|
||||
.exec('npm run build')
|
||||
.then(function (result) {
|
||||
// subject is now the result object
|
||||
// yields the 'result' object
|
||||
// {
|
||||
// code: 0,
|
||||
// stdout: "Files successfully built",
|
||||
@@ -53,61 +74,77 @@ cy
|
||||
})
|
||||
```
|
||||
|
||||
## Seed the database and assert it was successful
|
||||
**Seed the database and assert it was successful**
|
||||
|
||||
```javascript
|
||||
cy.exec("rake db:seed").its("code").should("eq", 0)
|
||||
cy.exec('rake db:seed').its('code').should('eq', 0)
|
||||
```
|
||||
|
||||
## Run an arbitrary script and assert its output
|
||||
**Run an arbitrary script and assert its output**
|
||||
|
||||
```javascript
|
||||
cy.exec("npm run my-script").its("stdout").should("contain", "Done running the script")
|
||||
cy.exec('npm run my-script').its('stdout').should('contain', 'Done running the script')
|
||||
```
|
||||
|
||||
## Change the timeout
|
||||
**Write to a file to create a fixture from response body**
|
||||
```javascript
|
||||
cy.server()
|
||||
cy.route('POST', '/comments').as('postComment')
|
||||
cy.get('.add-comment').click()
|
||||
cy.wait('@postComment').then(function(xhr){
|
||||
cy.exec(`echo ${JSON.stringify(xhr.responseBody)} >cypress/fixtures/comment.json`)
|
||||
cy.fixture('comment.json').should('deep.eq', xhr.responseBody)
|
||||
})
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
**Change the timeout**
|
||||
|
||||
You can increase the time allowed to execute the command, although *we don't recommend executing commands that take a long time to exit*.
|
||||
|
||||
Cypress will *not* continue running any other commands until `.exec()` has finished, so a long-running command will drastically slow down your test cycle.
|
||||
|
||||
```javascript
|
||||
// will fail if script takes longer than 20 seconds to finish
|
||||
cy.exec("npm run build", { timeout: 20000 });
|
||||
cy.exec('npm run build', { timeout: 20000 });
|
||||
```
|
||||
|
||||
## Choose not to fail on non-zero exit and assert on code and stderr
|
||||
**Choose to not fail on non-zero exit and assert on code and stderr**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.exec("man bear pig", { failOnNonZeroExit: false })
|
||||
.its("code").should("eq", 1)
|
||||
.its("stderr").should("contain", "No manual entry for bear")
|
||||
.exec('man bear pig', { failOnNonZeroExit: false })
|
||||
.its('code').should('eq', 1)
|
||||
.its('stderr').should('contain', 'No manual entry for bear')
|
||||
```
|
||||
|
||||
## Specify environment variables
|
||||
**Specify environment variables**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.exec("echo $USERNAME", { env: { USERNAME: "johndoe" } })
|
||||
.its("stdout").should("contain", "johndoe")
|
||||
.exec('echo $USERNAME', { env: { USERNAME: 'johndoe' } })
|
||||
.its('stdout').should('contain', 'johndoe')
|
||||
```
|
||||
|
||||
## Write to a file to create a fixture from response body
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route("POST", "/comments").as("postComment")
|
||||
.get(".add-comment").click()
|
||||
.wait("@postComment").then(function(xhr){
|
||||
cy
|
||||
.exec("echo '" + JSON.stringify(xhr.responseBody) + "'>cypress/fixtures/comment.json")
|
||||
.fixture("comment.json").should("deep.eq", xhr.responseBody)
|
||||
})
|
||||
```
|
||||
# Notes
|
||||
|
||||
**Commands that do not exit are not supported**
|
||||
|
||||
`.exec()` does not support commands that don't exit, such as:
|
||||
|
||||
- `rails server`
|
||||
- A task that runs a watch
|
||||
- Any process that needs to be manually interrupted to stop
|
||||
|
||||
A command must exit within the `execTimeout` or Cypress will kill the command's process and fail the current test.
|
||||
|
||||
# Command Log
|
||||
|
||||
## List the contents of cypress.json
|
||||
**List the contents of cypress.json**
|
||||
|
||||
```javascript
|
||||
cy.exec("cat cypress.json")
|
||||
cy.exec('cat cypress.json')
|
||||
```
|
||||
|
||||
The command above will display in the command log as:
|
||||
@@ -117,3 +154,9 @@ The command above will display in the command log as:
|
||||
When clicking on the `exec` command within the command log, the console outputs the following:
|
||||
|
||||
<img width="758" alt="screen shot of console output" src="https://cloud.githubusercontent.com/assets/1157043/15969867/e3ab646e-2eff-11e6-9199-987ca2f74025.png">
|
||||
|
||||
# See also
|
||||
|
||||
- [request](https://on.cypress.io/api/request)
|
||||
- [readFile](https://on.cypress.io/api/readFile)
|
||||
- [writeFile](https://on.cypress.io/api/writeFile)
|
||||
|
||||
@@ -4,31 +4,64 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get DOM elements that match a specific selector. Opposite of [`cy.not()`](https://on.cypress.io/api/not)
|
||||
Get the DOM elements that match a specific selector.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.filter` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
{% note info %}
|
||||
Opposite of [`.not()`](https://on.cypress.io/api/not)
|
||||
{% endnote %}
|
||||
|
||||
# [cy.filter( *selector* )](#selector-usage)
|
||||
# Syntax
|
||||
|
||||
Reduce the set of matched DOM elements to those that match the selector.
|
||||
```javascript
|
||||
.filter(selector)
|
||||
.filter(selector, options)
|
||||
```
|
||||
|
||||
# Options
|
||||
## Usage
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.filter`.
|
||||
`.filter()` requires being chained off another cy command that *yields* a DOM element or DOM elements.
|
||||
|
||||
**cy.filter( *selector*, *options* )**
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.get('td').filter('.users') // Yield all el's with class '.users'
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.filter('.animated') // Errors, cannot be chained off 'cy'
|
||||
cy.location().filter() // Errors, 'location' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
A selector used to filter matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.filter()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
|
||||
# Selector Usage
|
||||
## Yields
|
||||
|
||||
## Filter the current subject to the element with the class `active`.
|
||||
`.filter()` yields the new DOM elements found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.filter()` will continue to look for the filtered element(s) for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Selector
|
||||
|
||||
**Filter the current subject to the elements with the class `active`.**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -41,16 +74,16 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
// returns <li>About</li>
|
||||
cy.get("ul").find(">li").filter(".active")
|
||||
// yields <li>About</li>
|
||||
cy.get('ul').find('>li').filter('.active')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Filter the `li`'s to the `li` with the class `active`.
|
||||
**Filter the `li`'s to the `li` with the class `active`.**
|
||||
|
||||
```javascript
|
||||
cy.get(".left-nav>.nav").find(">li").filter(".active")
|
||||
cy.get('.left-nav>.nav').find('>li').filter('.active')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -61,6 +94,6 @@ When clicking on the `filter` command within the command log, the console output
|
||||
|
||||
<img width="503" alt="screen shot 2015-11-27 at 2 16 09 pm" src="https://cloud.githubusercontent.com/assets/1271364/11447266/74b643a4-9511-11e5-8b42-6f6dfbdfb2a8.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [not](https://on.cypress.io/api/not)
|
||||
|
||||
@@ -4,31 +4,60 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the descendents DOM elements of a specific selector.
|
||||
Get the descendent DOM elements of a specific selector.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.find` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.find( *selector* )](#selector-usage)
|
||||
```javascript
|
||||
.find(selector)
|
||||
.find(selector, options)
|
||||
```
|
||||
|
||||
Get the descendants of each DOM element in the current set of matched DOM elements within the selector.
|
||||
## Usage
|
||||
|
||||
# Options
|
||||
`.find()` requires being chained off another cy command that *yields* a DOM element or DOM elements.
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.find`.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
**cy.find( *selector*, *options* )**
|
||||
```javascript
|
||||
cy.get('.article').find('footer') // Yields 'footer' within '.article'
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.find('.progress') // Errors, cannot be chained off 'cy'
|
||||
cy.exec('node start').find() // Errors, 'exec' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
A selector used to filter matching descendent DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.find()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element(s)
|
||||
|
||||
# Selector Usage
|
||||
## Yields
|
||||
|
||||
## Get li's within parent
|
||||
`.find()` yields the new DOM elements found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.find()` will continue to look for the filtered element(s) for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Selector
|
||||
|
||||
**Get li's within parent**
|
||||
|
||||
```html
|
||||
<ul id="parent">
|
||||
@@ -39,15 +68,15 @@ Option | Default | Notes
|
||||
|
||||
```javascript
|
||||
// returns [<li class="first"></li>, <li class="second"></li>]
|
||||
cy.get("#parent").find("li")
|
||||
cy.get('#parent').find('li')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Find the `li`'s within the nav
|
||||
**Find the `li`'s within the nav**
|
||||
|
||||
```javascript
|
||||
cy.get(".left-nav>.nav").find(">li")
|
||||
cy.get('.left-nav>.nav').find('>li')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -58,6 +87,6 @@ When clicking on the `find` command within the command log, the console outputs
|
||||
|
||||
<img width="516" alt="screen shot 2015-11-27 at 2 19 54 pm" src="https://cloud.githubusercontent.com/assets/1271364/11447312/fa3679cc-9511-11e5-9bea-904f8c70063d.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [get](https://on.cypress.io/api/get)
|
||||
|
||||
@@ -6,29 +6,54 @@ description: ''
|
||||
|
||||
Get the first DOM element within a set of DOM elements.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.first` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.first()](#usage)
|
||||
```javascript
|
||||
.first()
|
||||
.first(options)
|
||||
```
|
||||
|
||||
Reduce the set of matched DOM elements to the first in the set.
|
||||
## Usage
|
||||
|
||||
# Options
|
||||
`.first()` requires being chained off another cy command that *yields* a DOM element or set of DOM elements.
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.first`.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
**cy.first(*options* )**
|
||||
```javascript
|
||||
cy.get('nav a').first() // Yield first link in nav
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.first() // Errors, cannot be chained off 'cy'
|
||||
cy.getCookies().first() // Errors, 'getCookies' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.first`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Get the first list item in a list.
|
||||
`.first()` yields the new DOM element found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.first()` will continue to look for the first element for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## First element
|
||||
|
||||
**Get the first list item in a list.**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -40,16 +65,16 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
// returns <li class="one">Knick knack on my thumb</li>
|
||||
cy.get("ul").first()
|
||||
// yields <li class="one">Knick knack on my thumb</li>
|
||||
cy.get('ul').first()
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Find the first `input` in the `form`
|
||||
**Find the first `input` in the `form`**
|
||||
|
||||
```javascript
|
||||
cy.get("form").find("input").first()
|
||||
cy.get('form').find('input').first()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -60,6 +85,6 @@ When clicking on `first` within the command log, the console outputs the followi
|
||||
|
||||
<img width="616" alt="screen shot 2015-11-29 at 12 28 23 pm" src="https://cloud.githubusercontent.com/assets/1271364/11458771/db8cb516-9694-11e5-86c2-cf3bbb9a666d.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [last](https://on.cypress.io/api/last)
|
||||
|
||||
@@ -4,68 +4,97 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Load a fixed set of data located in a file.
|
||||
|
||||
{% note info New to Cypress? %}
|
||||
[Read about Creating Fixtures first.](https://on.cypress.io/guides/creating-fixtures)
|
||||
{% endnote %}
|
||||
|
||||
Loads a single fixture file. Image fixtures will be sent as `base64`.
|
||||
# Syntax
|
||||
|
||||
If an extension is omitted, Cypress will attempt to resolve the fixture by order of these extensions:
|
||||
```javascript
|
||||
.fixture(filePath)
|
||||
.fixture(filePath, encoding)
|
||||
.fixture(filePath, options)
|
||||
.fixture(filePath, encoding, options)
|
||||
```
|
||||
|
||||
* `.json`
|
||||
* `.js`
|
||||
* `.coffee`
|
||||
* `.html`
|
||||
* `.txt`
|
||||
* `.csv`
|
||||
* `.png`
|
||||
* `.jpg`
|
||||
* `.jpeg`
|
||||
* `.gif`
|
||||
* `.tif`
|
||||
* `.tiff`
|
||||
* `.zip`
|
||||
## Usage
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the contents of the file, formatted by file extension |
|
||||
| **Timeout** | `cy.fixture` will wait up for the duration of [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the server to process this command. |
|
||||
`.fixture()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
# [cy.fixture( *fixture* )](#single-fixture-usage)
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
Loads the fixture at the specified filepath within the [`fixturesFolder`](https://on.cypress.io/guides/configuration#folders), which defaults to `cypress/fixtures`.
|
||||
```javascript
|
||||
cy.fixture('users').as('usersJson') // load data from users.json
|
||||
cy.fixture('logo.png').then(function(logo){
|
||||
// load data from logo.png
|
||||
})
|
||||
```
|
||||
|
||||
# [cy.fixture( *fixture*, *encoding* )](#encoding)
|
||||
## Arguments
|
||||
|
||||
Loads the fixture at the specified filepath within the [`fixturesFolder`](https://on.cypress.io/guides/configuration#folders), which defaults to `cypress/fixtures`, using the encoding specified when reading the file.
|
||||
**{% fa fa-angle-right %} filePath** ***(String)***
|
||||
|
||||
# Options
|
||||
A path to a file within the [`fixturesFolder`](https://on.cypress.io/guides/configuration#folders) (which defaults to `cypress/fixtures`).
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.fixture`.
|
||||
You can nest fixtures within folders and reference them by defining the path from the fixturesFolder:
|
||||
|
||||
**[cy.fixture( *fixture*, *options* )](#options-usage)**
|
||||
```javascript
|
||||
cy.fixture('users/admin.json') // Get data from {fixturesFolder}/users/admin.json
|
||||
```
|
||||
|
||||
**[cy.fixture( *fixture*, *encoding*, *options* )](#options-usage)**
|
||||
**{% fa fa-angle-right %} encoding** ***(String)***
|
||||
|
||||
The encoding to be used when reading the file. The following encodings are supported:
|
||||
|
||||
* `ascii`
|
||||
* `base64`
|
||||
* `binary`
|
||||
* `hex`
|
||||
* `latin1`
|
||||
* `utf8`
|
||||
* `utf-8`
|
||||
* `ucs2`
|
||||
* `ucs-2`
|
||||
* `utf16le`
|
||||
* `utf-16le`
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.fixture()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the `cy.fixture` command to be processed
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the command to be processed
|
||||
|
||||
# Single Fixture Usage
|
||||
## Yields
|
||||
|
||||
## Load the `users.json` fixture
|
||||
`.fixture()` yields the contents of the file. Formatting is determined by it's file extension.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.fixture` will wait up for the duration of [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the server to process the command.
|
||||
|
||||
# Examples
|
||||
|
||||
## JSON
|
||||
|
||||
**Load a `users.json` fixture**
|
||||
|
||||
```javascript
|
||||
cy.fixture("users.json")
|
||||
cy.fixture('users.json').as('usersData')
|
||||
```
|
||||
|
||||
## Omit the fixture file's extension
|
||||
**Omit the fixture file's extension**
|
||||
|
||||
When no extension is passed to `.fixture()`, Cypress will search for files with the specified name within the [`fixturesFolder`](https://on.cypress.io/guides/configuration#folders) (which defaults to `cypress/fixtures`) and resolve the first one.
|
||||
|
||||
```javascript
|
||||
cy.fixture("admin")
|
||||
cy.fixture('admin').as('adminJSON')
|
||||
```
|
||||
|
||||
When no extension is passed to `cy.fixture`, Cypress will search for files with the specified name within the [`fixturesFolder`](https://on.cypress.io/guides/configuration#folders), which defaults to `cypress/fixtures`, and resolve the first one. The above example would resolve in the following order:
|
||||
The example above would resolve in the following order:
|
||||
|
||||
1. `{fixturesFolder}/admin.json`
|
||||
2. `{fixturesFolder}/admin.js`
|
||||
@@ -81,47 +110,96 @@ When no extension is passed to `cy.fixture`, Cypress will search for files with
|
||||
12. `{fixturesFolder}/admin.tiff`
|
||||
13. `{fixturesFolder}/admin.zip`
|
||||
|
||||
## Image fixtures will be sent by default as `base64`
|
||||
## Images
|
||||
|
||||
**Image fixtures are sent as `base64`**
|
||||
|
||||
```javascript
|
||||
cy.fixture("images/logo.png").then(function(logo){
|
||||
cy.fixture('images/logo.png').then(function(logo){
|
||||
// logo will be encoded as base64
|
||||
// and should look something like this:
|
||||
// aIJKnwxydrB10NVWqhlmmC+ZiWs7otHotSAAAOw==...
|
||||
})
|
||||
```
|
||||
|
||||
## Change encoding of Image fixture
|
||||
**Change encoding of Image fixture**
|
||||
|
||||
```javascript
|
||||
cy.fixture("images/logo.png", "binary").then(function(logo){
|
||||
cy.fixture('images/logo.png', 'binary').then(function(logo){
|
||||
// logo will be encoded as binary
|
||||
// and should look something like this:
|
||||
// 000000000000000000000000000000000000000000...
|
||||
})
|
||||
```
|
||||
|
||||
# Notes
|
||||
## Accessing Fixture Data
|
||||
|
||||
## Nesting
|
||||
|
||||
You can nest fixtures within folders and reference them by defining the path to the file:
|
||||
|
||||
`{fixturesFolder}/users/admin.json`
|
||||
**Using cy.then to access fixture data**
|
||||
|
||||
```javascript
|
||||
cy.fixture("users/admin.json")
|
||||
cy
|
||||
.fixture('users').then(function(json){
|
||||
cy.route('GET', '/users/**', json)
|
||||
})
|
||||
```
|
||||
|
||||
## Validation
|
||||
{% note info %}
|
||||
[Check out our example recipe using cy.fixture to bootstrap data for our application.](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/bootstrapping_app_test_data_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
Cypress will automatically validate your fixtures. If your `.json`, `.js`, or `.coffee` files contain syntax errors, they will automatically be shown in the Command Log.
|
||||
**Using an alias to access a fixture**
|
||||
|
||||
## Formatting
|
||||
You can make use of aliasing, [.as()](https://on.cypress.io/api/as), instead of working directly with the yielded data.
|
||||
|
||||
Cypress automatically formats your fixture files. That means you can paste in a single line of `json` and the next time Cypress serves this fixture, it will format / indent the `json`, which makes it easier to read and debug.
|
||||
Using an alias provides the benefit of terseness and readability. It also makes it easier to access the data later in your tests.
|
||||
|
||||
## Encoding
|
||||
```javascript
|
||||
cy
|
||||
.fixture('users').as('usersJSON')
|
||||
.route('GET', '/users/**', '@usersJSON')
|
||||
|
||||
// ...later on...
|
||||
|
||||
.then(function(){
|
||||
// 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(function(user) {
|
||||
user.firstName = 'Jane'
|
||||
cy.route('GET', '/users/1', user).as('getUser')
|
||||
})
|
||||
|
||||
cy.visit('/users')
|
||||
cy.wait('@getUser').then(function(xhr) {
|
||||
expect(xhr.requestBody.firstName).to.eq('Jane')
|
||||
})
|
||||
```
|
||||
|
||||
## Fixture Shortcuts
|
||||
|
||||
**Using `fixture` or `fx` shortcuts**
|
||||
|
||||
Fixtures can also be referenced directly without using the `.fixture()` command by using the special keywords: `fixture:` or `fx:` within [`.route()`](https://on.cypress.io/api/route).
|
||||
|
||||
```javascript
|
||||
cy.route('GET', '/users/**', 'fixture:users') // this works
|
||||
cy.route('GET', '/users/**', 'fx:users') // this also works
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
**Validation and Formatting**
|
||||
|
||||
Cypress automatically validates and formats your fixtures. If your `.json`, `.js`, or `.coffee` files contain syntax errors, they will be shown in the Command Log.
|
||||
|
||||
**Default Encoding**
|
||||
|
||||
Cypress automatically determines the encoding for the following file types:
|
||||
|
||||
@@ -139,96 +217,16 @@ Cypress automatically determines the encoding for the following file types:
|
||||
* `.tiff`
|
||||
* `.zip`
|
||||
|
||||
For other types of files, they will be read as `utf8` by default. You can specify a different encoding by passing it as the [second argument](https://on.cypress.io/api/fixture#-cy-fixture-fixture-encoding-section-encoding-).
|
||||
|
||||
```javascript
|
||||
cy.fixture("foo.bmp", "base64")
|
||||
```
|
||||
|
||||
The following encodings are supported:
|
||||
|
||||
* `ascii`
|
||||
* `base64`
|
||||
* `binary`
|
||||
* `hex`
|
||||
* `latin1`
|
||||
* `utf8`
|
||||
* `utf-8`
|
||||
* `ucs2`
|
||||
* `ucs-2`
|
||||
* `utf16le`
|
||||
* `utf-16le`
|
||||
|
||||
# Usage with `cy.route()`
|
||||
|
||||
## Using fixture or fx shortcuts
|
||||
|
||||
Fixtures can be referenced directly by the special keywords: `fixture:` or `fx:`.
|
||||
|
||||
This enables you to set a fixture as the response for a route without having to first use the `cy.fixture` command.
|
||||
|
||||
```javascript
|
||||
cy.route("GET", /users/, "fixture:users") // this works
|
||||
cy.route("GET", /users/, "fx:users") // this also works
|
||||
```
|
||||
|
||||
This saves you from having to explicitly load the fixture first (like [below](https://on.cypress.io/api/fixture#using-cy-then-to-access-fixture-data)).
|
||||
|
||||
## Using cy.then to access fixture data
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.fixture("users").then(function(json){
|
||||
cy.route("GET", /users/, json)
|
||||
})
|
||||
```
|
||||
|
||||
{% note info Using cy.fixture for response data %}
|
||||
[Check out our example recipe using cy.fixture to bootstrap data for our application.](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/bootstrapping_app_test_data_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
## Using an alias to access a fixture
|
||||
|
||||
However if you still need access to the fixture data, instead of [yielding the fixture's data](https://on.cypress.io/api/fixture#using-cy-then-to-access-fixture-data), we can make use of [aliasing](https://on.cypress.io/guides/using-aliases).
|
||||
|
||||
Using an alias provides the benefit of terseness and readability.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.fixture("users").as("usersJSON")
|
||||
.route("GET", /users/, "@usersJSON")
|
||||
|
||||
// ...later on...
|
||||
|
||||
.then(function(){
|
||||
// we have access to this.usersJSON since it was aliased
|
||||
this.usersJSON
|
||||
})
|
||||
```
|
||||
|
||||
## Modifying fixture data before using it
|
||||
|
||||
You can also modify fixture data directly before passing it along to the route.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.fixture("user").then(function(user){
|
||||
user.firstName = "Jane"
|
||||
|
||||
cy.route("GET", "/users/1", user)
|
||||
})
|
||||
.visit("/users")
|
||||
.get(".user").should("include", "Jane")
|
||||
})
|
||||
```
|
||||
For other types of files, they will be read as `utf8` by default, unless specified in the second argument of `.fixture()`
|
||||
|
||||
# Command Log
|
||||
|
||||
## `fixture` does *not* log in the command log
|
||||
**`fixture` does *not* log in the command log**
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [Guide: Creating Fixtures](https://on.cypress.io/guides/creating-fixtures)
|
||||
- [Recipe: Bootstrapping App Test Data](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/bootstrapping_app_test_data_spec.js)
|
||||
- [readFile](https://on.cypress.io/api/readfile)
|
||||
- [route](https://on.cypress.io/api/route)
|
||||
- [then](https://on.cypress.io/api/then)
|
||||
|
||||
@@ -4,50 +4,87 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Focus on a DOM element. If there is currently a different DOM element currently with focus, Cypress will issue a `blur` event to that element first.
|
||||
Focus on a DOM element.
|
||||
|
||||
**The following events are fired during focus:** `focusin`, `focus`
|
||||
# Syntax
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.focus` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
```javascript
|
||||
.focus()
|
||||
.focus(options)
|
||||
```
|
||||
|
||||
# [cy.focus()](#usage)
|
||||
## Usage
|
||||
|
||||
Focus on the DOM element found in the previous command.
|
||||
`.focus()` requires being chained off another cy command that *yields* a DOM element.
|
||||
|
||||
# Options
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.get('input').first().focus() // Focus on the first input
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.focus('#search') // Errors, cannot be chained off 'cy'
|
||||
cy.window().focus() // Errors, 'window' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.focus`.
|
||||
|
||||
**cy.focus( *options* )**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Focus on the current subject.
|
||||
`.focus()` yields the new DOM element that was focused.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.focus()` will continue to try to focus the element for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Focus
|
||||
|
||||
**Focus on an input**
|
||||
|
||||
```javascript
|
||||
cy.get("[name='comment']").focus()
|
||||
cy.get('[type="input"]').focus()
|
||||
```
|
||||
|
||||
Focus, type, and blur the current subject.
|
||||
**Focus, type, and blur a textarea**
|
||||
|
||||
```javascript
|
||||
// returns the <textarea> for further chaining
|
||||
cy.get("[name='comment']").focus().type("Nice Product!").blur()
|
||||
// yields the <textarea> for further chaining
|
||||
cy.get('textarea').focus().type('Nice Product!').blur()
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
**Cypress blurs other focused elements first**
|
||||
|
||||
If there is currently a different DOM element with focus, Cypress issues a `blur` event to that element before running the `.focus()` command.
|
||||
|
||||
**`.focus()` can only be called on a valid focusable element.**
|
||||
|
||||
Ensure the element you are trying to call `.focus()` on is a [focusable element](https://www.w3.org/TR/html5/editing.html#focusable). Most commonly, you'll want to ensure that the element is not disabled, although there are [other factors](https://www.w3.org/TR/html5/editing.html#focusable).
|
||||
|
||||
**`.focus()` can time out because your browser did not receive any focus events.**
|
||||
|
||||
If you see this error, you may want to ensure that the main browser window is currently focused. This means not being focused in debugger or any other window when the command is run.
|
||||
|
||||
# Command Log
|
||||
|
||||
## Focus the textarea.
|
||||
**Focus the textarea**
|
||||
|
||||
```javascript
|
||||
cy.get("[name='comment']").focus()
|
||||
cy.get('[name="comment"]').focus()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -58,17 +95,7 @@ When clicking on the `focus` command within the command log, the console outputs
|
||||
|
||||
<img width="526" alt="screen shot 2015-11-27 at 1 33 00 pm" src="https://cloud.githubusercontent.com/assets/1271364/11446857/703fa6c2-950b-11e5-9686-ce6b558cfd92.png">
|
||||
|
||||
# Errors
|
||||
|
||||
## cy.focus() can only be called on a valid focusable element.
|
||||
|
||||
Ensure the element you are trying to call `cy.focus()` on is a [focusable element](https://www.w3.org/TR/html5/editing.html#focusable). Most commonly, you'll want to ensure that the element is not disabled although there are [other factors](https://www.w3.org/TR/html5/editing.html#focusable).
|
||||
|
||||
## cy.focus() timed out because your browser did not receive any focus events. This is a known bug in Chrome when it is not the currently focused window.
|
||||
|
||||
If you see this error, you may want to ensure that the main browser window is currently focused. This means not being focused in debugger or any other window when the command is executed.
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [focused](https://on.cypress.io/api/focused)
|
||||
- [blur](https://on.cypress.io/api/blur)
|
||||
|
||||
@@ -6,45 +6,71 @@ description: ''
|
||||
|
||||
Get the DOM element that is currently focused.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the current DOM element that is focused or `null` |
|
||||
| **Timeout** | `cy.focused` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.focused()](#usage)
|
||||
```javascript
|
||||
.focused()
|
||||
.focused(options)
|
||||
```
|
||||
|
||||
Get the focused DOM element.
|
||||
## Usage
|
||||
|
||||
# Options
|
||||
`.focused()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.focused()
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Objecdt)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.focused`.
|
||||
|
||||
**cy.focused( *options* )**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Get the element that is focused.
|
||||
`.filter()` yields the new DOM elements found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.filter()` will continue to look for the focuse element for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Focused
|
||||
|
||||
**Get the element that is focused.**
|
||||
|
||||
```javascript
|
||||
cy.focused()
|
||||
cy.focused().then(function($el) {
|
||||
// do something with $el
|
||||
})
|
||||
```
|
||||
|
||||
## Make an assertion on the focused element.
|
||||
**Blur the element with focus.**
|
||||
|
||||
```javascript
|
||||
cy.focused().should("have.attr", "name", "username")
|
||||
cy.focused().blur()
|
||||
```
|
||||
|
||||
**Make an assertion on the focused element.**
|
||||
|
||||
```javascript
|
||||
cy.focused().should('have.attr', 'name', 'username')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Make an assertion on the focused element.
|
||||
**Make an assertion on the focused element.**
|
||||
|
||||
```javascript
|
||||
cy.focused().should("have.attr", "name").and("eq", "num")
|
||||
cy.focused().should('have.attr', 'name').and('eq', 'num')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -55,7 +81,7 @@ When clicking on the `focused` command within the command log, the console outpu
|
||||
|
||||
<img width="407" alt="screen shot 2015-11-27 at 1 02 02 pm" src="https://cloud.githubusercontent.com/assets/1271364/11446771/d104a6d0-9509-11e5-9464-2e397cb1eb24.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [focus](https://on.cypress.io/api/focus)
|
||||
- [blur](https://on.cypress.io/api/blur)
|
||||
|
||||
@@ -6,112 +6,127 @@ description: ''
|
||||
|
||||
Get one or more DOM elements by selector or [alias](https://on.cypress.io/guides/using-aliases).
|
||||
|
||||
`cy.get` supports all CSS based selectors. It is analogous to jQuery's `$(...)` in that any selector you pass to jQuery you can also pass to `cy.get`.
|
||||
# Syntax
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.get` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
```javascript
|
||||
.get(selector)
|
||||
.get(alias)
|
||||
.get(selector, options)
|
||||
```
|
||||
|
||||
# [cy.get( *selector* )](#selector-usage)
|
||||
## Usage
|
||||
|
||||
Finds one or more DOM elements based on the selector.
|
||||
`.get()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
# [cy.get( *alias* )](#alias-usage)
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
{% note info New to Cypress? %}
|
||||
[Read about using aliases first.](https://on.cypress.io/guides/using-aliases)
|
||||
```javascript
|
||||
cy.get('.list>li')
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
A selector used to filter matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} alias** ***(String)***
|
||||
|
||||
An alias as defined using the [`.as()`](https://on.cypress.io/api/as) command and referenced with the `@` character and the name of the alias.
|
||||
|
||||
Internally, Cypress keeps a cache of all aliased elements. If the element currently exists in the DOM, it is immediately returned. If the element no longer exists, Cypress will re-query the element based on the previous selector path defined before [`.as()`](https://on.cypress.io/api/as) to find it again.
|
||||
|
||||
{% note info %}
|
||||
[Read about using aliases here.](https://on.cypress.io/guides/using-aliases)
|
||||
{% endnote %}
|
||||
|
||||
You can pass in the `@` character and the name of an alias as a parameter to find an [aliased](https://on.cypress.io/guides/using-aliases) element.
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Internally Cypress keeps a cache of all aliased elements. If the element currently exists in the DOM, it is immediately returned. If the element no longer exists, Cypress will re-query the element based on the previous selector path to find it again.
|
||||
|
||||
# Options
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.get`.
|
||||
|
||||
**cy.get( *selector*, *options* )**
|
||||
**cy.get( *alias*, *options* )**
|
||||
Pass in an options object to change the default behavior of `.get()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
|
||||
# Selector Usage
|
||||
## Yields
|
||||
|
||||
## Find the element with an id of main
|
||||
`.get()` yields the new DOM element(s) found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.get()` will continue to look for the elements for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Selector
|
||||
|
||||
**Get the input element**
|
||||
|
||||
```javascript
|
||||
cy.get("#main")
|
||||
cy.get('input').should('be.disabled')
|
||||
```
|
||||
|
||||
## Find the first `li` descendent within a `ul`
|
||||
**Find the first `li` descendent within a `ul`**
|
||||
|
||||
```javascript
|
||||
cy.get("ul li:first")
|
||||
cy.get('ul li:first').should('have.class', 'active')
|
||||
```
|
||||
|
||||
## Find the element with class dropdown-menu and click it.
|
||||
**Find the `.dropdown-menu` and click it.**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get(".dropdown-menu").click()
|
||||
|
||||
// Break out of the previous command chain and
|
||||
// query for #search from the root document.
|
||||
.get("#search").type("mogwai")
|
||||
cy.get('.dropdown-menu').click()
|
||||
```
|
||||
|
||||
## Reset the current scope in a [`cy.within`](https://on.cypress.io/api/within)
|
||||
## Get Within
|
||||
|
||||
**`.get()` in a [`.within()`](https://on.cypress.io/api/within)**
|
||||
|
||||
Since `.get()` is chained off of `cy`, it always looks for the selector within the entire `document`. The only exception is when used inside a [`.within()`]() command.
|
||||
|
||||
```javascript
|
||||
// Find form and scope all new queries to within form.
|
||||
cy.get("form").within(function(){
|
||||
cy
|
||||
// Find the input within form and type Pamela
|
||||
.get("input").type("Pamela")
|
||||
// Find the element textarea within form and type in it
|
||||
.get("textarea").type("is a developer")
|
||||
cy.get('form').within(function(){
|
||||
cy.get('input').type('Pamela') // Get the input within form
|
||||
cy.get('textarea').type('is a developer') // Find the textarea within form
|
||||
})
|
||||
```
|
||||
|
||||
# Alias Usage
|
||||
## Alias
|
||||
|
||||
For a detailed explanation of aliasing, [read more about aliasing here](https://on.cypress.io/guides/using-aliases).
|
||||
|
||||
## Retrieve aliased `todos` elements
|
||||
**Retrieve aliased `todos` elements**
|
||||
|
||||
```javascript
|
||||
cy.get("ul#todos").as("todos")
|
||||
cy.get('ul#todos').as('todos')
|
||||
|
||||
//...hack hack hack...
|
||||
|
||||
//later retrieve the todos
|
||||
cy.get("@todos")
|
||||
cy.get('@todos')
|
||||
```
|
||||
|
||||
## Alias the `submitBtn` in a `beforeEach`
|
||||
**Get the `submitBtn`**
|
||||
|
||||
```javascript
|
||||
beforeEach(function(){
|
||||
cy.get("button[type=submit]").as("submitBtn")
|
||||
cy.get('button[type=submit]').as('submitBtn')
|
||||
})
|
||||
|
||||
it("disables on click", function(){
|
||||
cy.get("@submitBtn").should("be.disabled")
|
||||
it('disables on click', function(){
|
||||
cy.get('@submitBtn').should('be.disabled')
|
||||
})
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Get an input and assert on the value
|
||||
**Get an input and assert on the value**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("input[name='firstName']")
|
||||
.should("have.value", "Homer")
|
||||
.get('input[name='firstName']')
|
||||
.should('have.value', 'Homer')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -122,9 +137,9 @@ When clicking on the `get` command within the command log, the console outputs t
|
||||
|
||||
<img width="543" alt="screen shot 2015-11-27 at 1 24 45 pm" src="https://cloud.githubusercontent.com/assets/1271364/11446809/61a6f4f4-950a-11e5-9b23-a9efa1fbccfc.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [as](https://on.cypress.io/api/as)
|
||||
- [contains](https://on.cypress.io/api/contains)
|
||||
- [within](https://on.cypress.io/api/within)
|
||||
- [find](https://on.cypress.io/api/find)
|
||||
- [root](https://on.cypress.io/api/root)
|
||||
- [within](https://on.cypress.io/api/within)
|
||||
|
||||
@@ -4,64 +4,82 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get a browser cookie.
|
||||
Get a browser cookie by it's name.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | a cookie object literal |
|
||||
| **Timeout** | `cy.getCookie` will wait up for the duration of [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the automation server to process this command. |
|
||||
# Syntax
|
||||
|
||||
# [cy.getCookie( *name* )](#usage)
|
||||
```javascript
|
||||
.getCookie(name)
|
||||
.getCookie(name, options)
|
||||
```
|
||||
|
||||
Gets a browser cookie by its name.
|
||||
## Usage
|
||||
|
||||
This object will have the following properties:
|
||||
`.getCookie()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
| Properties |
|
||||
| --- |
|
||||
| `name` |
|
||||
| `value` |
|
||||
| `path` |
|
||||
| `domain` |
|
||||
| `httpOnly` |
|
||||
| `secure` |
|
||||
| `expiry` |
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# Options
|
||||
```javascript
|
||||
cy.getCookie('auth_key')
|
||||
```
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.getCookie`.
|
||||
## Arguments
|
||||
|
||||
**cy.getCookie( *name*, *options* )**
|
||||
**{% fa fa-angle-right %} name** ***(String)***
|
||||
|
||||
The name of the cookie to get.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.getCookie()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the `cy.getCookie` command to be processed
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the `.getCookie()` command to be processed
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Get `session_id` cookie after logging in
|
||||
`.getCookie()` yields a cookie object literal with the following properties:
|
||||
|
||||
In this example, on first login our server sends us back a session cookie.
|
||||
- `name`
|
||||
- `value`
|
||||
- `path`
|
||||
- `domain`
|
||||
- `httpOnly`
|
||||
- `secure`
|
||||
- `expiry`
|
||||
|
||||
## Timeout
|
||||
|
||||
`.getCookie()` will continue to look for the cookie for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Get Cookie
|
||||
|
||||
**Get `session_id` cookie after logging in**
|
||||
|
||||
In this example, on first login, our server sends us back a session cookie.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.login('bob@example.com', 'p@ssw0rd') // example of a custom command
|
||||
.getCookie('session_id')
|
||||
.should('have.property', 'value', '189jd09sufh33aaiidhf99d09')
|
||||
// assume we just logged in
|
||||
cy.contains('Login').click()
|
||||
cy.url().should('include', 'profile')
|
||||
cy.getCookie('session_id')
|
||||
.should('have.property', 'value', '189jd09su')
|
||||
```
|
||||
|
||||
{% note info Using cy.getCookie to test login %}
|
||||
{% note info %}
|
||||
Check out our example recipes using cy.getCookie to test [logging in using HTML web forms](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_html_web_form_spec.js), [logging in using XHR web forms](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_xhr_web_form_spec.js) and [logging in with single sign on](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_single_sign_on_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
# Command Log
|
||||
|
||||
## Get cookie
|
||||
**Get cookie**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.getCookie('fakeCookie1')
|
||||
cy.getCookie('fakeCookie1')
|
||||
.should('have.property', 'value', '123ABC')
|
||||
```
|
||||
|
||||
@@ -73,7 +91,7 @@ When clicking on `getCookie` within the command log, the console outputs the fol
|
||||
|
||||

|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [clearCookie](https://on.cypress.io/api/clearcookie)
|
||||
- [clearCookies](https://on.cypress.io/api/clearcookies)
|
||||
|
||||
@@ -4,50 +4,68 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Gets all of the browser cookies.
|
||||
Get all of the browser cookies.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | an array of cookie objects |
|
||||
| **Timeout** | `cy.getCookies` will wait up for the duration of [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the automation server to process this command. |
|
||||
# Syntax
|
||||
|
||||
# [cy.getCookies()](#usage)
|
||||
```javascript
|
||||
.getCookies()
|
||||
.getCookies(options)
|
||||
```
|
||||
|
||||
Gets the browser cookies.
|
||||
## Usage
|
||||
|
||||
Each cookie object will have the following properties:
|
||||
`.getCookies()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
| Properties |
|
||||
| --- |
|
||||
| `name` |
|
||||
| `value` |
|
||||
| `path` |
|
||||
| `domain` |
|
||||
| `httpOnly` |
|
||||
| `secure` |
|
||||
| `expiry` |
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# Options
|
||||
```javascript
|
||||
cy.getCookies()
|
||||
```
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.getCookies`.
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.getCookies()`.
|
||||
|
||||
**[cy.getCookies(*options* )](#options-usage)**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the `cy.getCookies` command to be processed
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the `.getCookies()` command to be processed
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Get cookies after logging in
|
||||
`.getCookies()` yields an array cookie objects. Each cookie object has the following properties:
|
||||
|
||||
- `name`
|
||||
- `value`
|
||||
- `path`
|
||||
- `domain`
|
||||
- `httpOnly`
|
||||
- `secure`
|
||||
- `expiry`
|
||||
|
||||
|
||||
## Timeout
|
||||
|
||||
`.getCookies()` will continue to look for cookies for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Get Cookies
|
||||
|
||||
**Get cookies after logging in**
|
||||
|
||||
In this example, on first login our server sends us back a session cookie.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.login("bob@example.com", "p@ssw0rd") // example of a custom command
|
||||
.getCookies()
|
||||
// assume we just logged in
|
||||
cy.contains('Login').click()
|
||||
cy.url().should('include', 'profile')
|
||||
cy.getCookies()
|
||||
.should('have.length', 1)
|
||||
.then(function(cookies) {
|
||||
expect(cookies[0]).to.have.property('name', 'session_id')
|
||||
@@ -56,21 +74,17 @@ cy
|
||||
|
||||
# Command Log
|
||||
|
||||
## Get cookies
|
||||
**Get cookies**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.getCookies()
|
||||
.should('have.length', 1)
|
||||
.then( function(cookies) {
|
||||
// each cookie has these properties
|
||||
expect(cookies[0]).to.have.property('name', 'fakeCookie1')
|
||||
expect(cookies[0]).to.have.property('value', '123ABC')
|
||||
expect(cookies[0]).to.have.property('domain')
|
||||
expect(cookies[0]).to.have.property('httpOnly')
|
||||
expect(cookies[0]).to.have.property('path')
|
||||
expect(cookies[0]).to.have.property('secure')
|
||||
})
|
||||
cy.getCookies().should('have.length', 1).then(function(cookies) {
|
||||
expect(cookies[0]).to.have.property('name', 'fakeCookie1')
|
||||
expect(cookies[0]).to.have.property('value', '123ABC')
|
||||
expect(cookies[0]).to.have.property('domain')
|
||||
expect(cookies[0]).to.have.property('httpOnly')
|
||||
expect(cookies[0]).to.have.property('path')
|
||||
expect(cookies[0]).to.have.property('secure')
|
||||
})
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -81,7 +95,7 @@ When clicking on `getCookies` within the command log, the console outputs the fo
|
||||
|
||||

|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [clearCookie](https://on.cypress.io/api/clearcookie)
|
||||
- [clearCookies](https://on.cypress.io/api/clearcookies)
|
||||
|
||||
@@ -4,56 +4,83 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Navigate back or forward to the previous or next URL in the browser's history. If going forward or back causes a full page refresh, Cypress will wait for the new page to load before moving on to new commands. Cypress additionally handles situations where a page load was not caused (such as hash routing) and will resolve immediately.
|
||||
Navigate back or forward to the previous or next URL in the browser's history.
|
||||
|
||||
If going forward or back causes a full page refresh, Cypress will wait for the new page to load before moving on to new commands. Cypress additionally handles situations where a page load was not caused (such as hash routing) and will resolve immediately.
|
||||
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
.go(direction)
|
||||
.go(direction, options)
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`.go()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.go('back')
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} direction** ***(String, Number)***
|
||||
|
||||
The direction to navigate.
|
||||
|
||||
You can use `back` or `forward` to go one step back or forward. You could also navigate to a specific history position (`-1` goes back one page, `1` goes forward one page, etc).
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.go`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [pageLoadTimeout](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the navigation
|
||||
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the `window` object |
|
||||
| **Timeout** | `cy.go` will retry for the duration of the [pageLoadTimeout](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's [options](#options). |
|
||||
|
||||
# [cy.go( *direction* )](#direction-usage)
|
||||
## Yields
|
||||
|
||||
Navigate back or forward to the URL in a specific direction (`back` or `forward`).
|
||||
`.go()` yields the `window` object.
|
||||
|
||||
# [cy.go( *number* )](#number-usage)
|
||||
## Timeout
|
||||
|
||||
Navigate back or forward going to the URL within a specific history position (-1 goes back one page, 1 goes forward one page).
|
||||
`.go()` will retry for the duration of the [pageLoadTimeout](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's [options](#options).
|
||||
|
||||
# Options
|
||||
# Examples
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.go`.
|
||||
## Back / Forward
|
||||
|
||||
**cy.go( *direction*, *options* )**
|
||||
**cy.go( *number*, *options* )**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`timeout` | [pageLoadTimeout](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the visit
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Direction Usage
|
||||
|
||||
## Go back in browser's history
|
||||
**Go back in browser's history**
|
||||
|
||||
```javascript
|
||||
cy.go("back") // equivalent to clicking back button
|
||||
cy.go('back') // equivalent to clicking back button
|
||||
```
|
||||
|
||||
## Go forward in browser's history
|
||||
**Go forward in browser's history**
|
||||
|
||||
```javascript
|
||||
cy.go("forward") // equivalent to clicking forward button
|
||||
cy.go('forward') // equivalent to clicking forward button
|
||||
```
|
||||
|
||||
# Number Usage
|
||||
## Number
|
||||
|
||||
## Go back in browser's history
|
||||
**Go back in browser's history**
|
||||
|
||||
```javascript
|
||||
cy.go(-1) // equivalent to clicking back button
|
||||
```
|
||||
|
||||
## Go forward in browser's history
|
||||
**Go forward in browser's history**
|
||||
|
||||
```javascript
|
||||
cy.go(1) // equivalent to clicking forward button
|
||||
@@ -61,12 +88,12 @@ cy.go(1) // equivalent to clicking forward button
|
||||
|
||||
# Command Log
|
||||
|
||||
## Go back in browser's history
|
||||
**Go back in browser's history**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.visit("http://localhost:8000/folders")
|
||||
.go("back")
|
||||
.visit('http://localhost:8000/folders')
|
||||
.go('back')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -77,16 +104,6 @@ When clicking on the `get` command within the command log, the console outputs t
|
||||
|
||||

|
||||
|
||||
# Errors
|
||||
|
||||
## cy.go() accepts only a string or number argument
|
||||
|
||||
`cy.go()` specifically accepts the string arguments `back` or `forward` or a number argument to navigate to a specific position in the history.
|
||||
|
||||
## cy.go() cannot accept '0'. The number must be greater or less than '0'.
|
||||
|
||||
Ensure the number passed to `cy.go()` navigates forward or backward in history. For example, -1 goes back one page, 1 goes forward one page.
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [visit](https://on.cypress.io/api/visit)
|
||||
|
||||
@@ -4,38 +4,59 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the current URL hash. This is the same as [`cy.location().hash`](https://on.cypress.io/api/location)
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the current URL hash as a string, including the `#` character. If no `#` character is present, an empty string will be returned. |
|
||||
| **Timeout** | *cannot timeout* |
|
||||
|
||||
# [cy.hash()](#usage)
|
||||
|
||||
Get the current URL hash.
|
||||
|
||||
# Options
|
||||
{% note info %}
|
||||
This is the same as [`cy.location().hash`](https://on.cypress.io/api/location)
|
||||
{% endnote %}
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.hash`.
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
cy.hash()
|
||||
cy.hash(options)
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`.hash()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.hash()
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.hash()`.
|
||||
|
||||
**cy.hash( *options* )**
|
||||
**cy.hash( *options* )**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Assert that the hash is `#/users/1` given the remote URL: `http://localhost:8000/app/#/users/1`
|
||||
`.hash()` yields the current URL hash as a string including the `#` character. If no `#` character is present in the URL, then an empty string will be returned.
|
||||
|
||||
## Timeout
|
||||
|
||||
# Examples
|
||||
|
||||
## Hash
|
||||
|
||||
**Assert that hash is `#/users/1` given remote URL: `http://localhost:8000/app/#/users/1`**
|
||||
|
||||
```javascript
|
||||
// Hash returns #/users/1
|
||||
cy.hash().should("eq", "#/users/1") // => true
|
||||
// yields #/users/1
|
||||
cy.hash().should('eq', '#/users/1') // => true
|
||||
```
|
||||
|
||||
## Assert that the hash matches via RegExp
|
||||
**Assert that the hash matches via RegExp**
|
||||
|
||||
```html
|
||||
<ul id="users">
|
||||
@@ -46,36 +67,16 @@ cy.hash().should("eq", "#/users/1") // => true
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("#users li").find("a")
|
||||
.hash().should("match", /users\/.+$/) // => true
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
## Hash is a shortcut for `cy.location().hash`
|
||||
|
||||
These 3 assertions are all the same.
|
||||
|
||||
```javascript
|
||||
// 1. verbose
|
||||
cy.location().then(function(location){
|
||||
expect(location.hash).to.eq("#/users/1")
|
||||
})
|
||||
|
||||
// 2. better
|
||||
cy.location().its("hash").should("eq", "#/users/1")
|
||||
|
||||
// 3. best
|
||||
cy.hash().should("eq", "#/users/1")
|
||||
cy.get('#users li').find('a').click()
|
||||
cy.hash().should('match', /users\/.+$/) // => true
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Assert that the hash matches `#users/new`
|
||||
**Assert that the hash matches `#users/new`**
|
||||
|
||||
```javascript
|
||||
cy.hash().should("eq", "#users/new")
|
||||
cy.hash().should('eq', '#users/new')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -86,7 +87,7 @@ When clicking on `hash` within the command log, the console outputs the followin
|
||||
|
||||
<img width="472" alt="screen shot 2015-11-29 at 1 34 17 pm" src="https://cloud.githubusercontent.com/assets/1271364/11459153/f0aa6476-969d-11e5-9851-302957f9eb0f.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [location](https://on.cypress.io/api/location)
|
||||
- [url](https://on.cypress.io/api/url)
|
||||
|
||||
@@ -8,7 +8,7 @@ description: ''
|
||||
|
||||
If `cy.hover()` is used, an error will display and redirect you to this page.
|
||||
|
||||
## Workaround
|
||||
# Workaround
|
||||
|
||||
Sometimes an element has specific logic on hover and you *do* need to "hover" in Cypress. Maybe the element doesn't even display to be clickable until you hover over another element.
|
||||
|
||||
@@ -16,33 +16,33 @@ Oftentimes you can use [`cy.invoke`](https://on.cypress.io/api/invoke) or [`cy.w
|
||||
|
||||
**Example of showing an element in order to perform action**
|
||||
```javascript
|
||||
cy.get(".content").invoke("show").click()
|
||||
cy.get('.content').invoke('show').click()
|
||||
```
|
||||
|
||||
{% note info Dealing with hover and hidden elements %}
|
||||
[Check out our example recipe on testing hover and working with hidden elements](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/hover_hidden_elements_spec.js)
|
||||
{% note info %}
|
||||
[Check out our example recipe on testing hover and working with hidden elements](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/hover_hidden_elements.js)
|
||||
{% endnote %}
|
||||
|
||||
You can also force the action to be performed on the element regardless of whether the element is visible or not.
|
||||
|
||||
**Example of clicking on a hidden element**
|
||||
```javascript
|
||||
cy.get(".content").click({force: true})
|
||||
cy.get('.content').click({force: true})
|
||||
```
|
||||
|
||||
**Example of checking a hidden element**
|
||||
```javascript
|
||||
cy.get(".checkbox").check({force: true})
|
||||
cy.get('.checkbox').check({force: true})
|
||||
```
|
||||
|
||||
If the hover behavior depends on a JavaScript event like `mouseover`, you can trigger the event to achieve that behavior.
|
||||
|
||||
**Example of triggering a mouseover event**
|
||||
```javascript
|
||||
cy.get(".content").trigger("mouseover")
|
||||
cy.get('.content').trigger('mouseover')
|
||||
```
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [Recipe: Dealing with Hover and Hidden Elements](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/hover_hidden_elements_spec.js)
|
||||
- [invoke](https://on.cypress.io/api/invoke)
|
||||
|
||||
@@ -4,81 +4,113 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
`cy.invoke` invokes functions on the current subject.
|
||||
Invoke a function on the previously yielded subject.
|
||||
|
||||
If you want to call a regular property that is not a function on the current subject, use [`cy.its`](https://on.cypress.io/api/its).
|
||||
{% note info %}
|
||||
If you want to get a property that is not a function on the previously yielded subject, use [`.its()`](https://on.cypress.io/api/its).
|
||||
{% endnote %}
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the return value of the invoked property |
|
||||
| **Timeout** | `cy.invoke` cannot timeout unless you've added assertions. The assertions will retry for the duration of [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.invoke( *functionName* )](#function-usage)
|
||||
```javascript
|
||||
.invoke(functionName)
|
||||
.invoke(functionName, args...)
|
||||
```
|
||||
|
||||
Invokes the function with the specified name
|
||||
## Usage
|
||||
|
||||
# [cy.invoke( *functionName*, **arguments* )](#function-with-arguments-usage)
|
||||
`.invoke()` requires being chained off another cy command that *yields* an object with function properties.
|
||||
|
||||
Invokes the function with the specified name and forwards any additional arguments to the function call. There are no limits to the number of arguments.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# Function Usage
|
||||
```javascript
|
||||
cy.wrap({animate: fn}).invoke('animate') // Invoke the 'animate' function
|
||||
cy.get('.modal').invoke('show') // Invoke the jQuery 'show' function
|
||||
```
|
||||
|
||||
## Assert on a function after invoke
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.invoke('convert') // Errors, cannot be chained off 'cy'
|
||||
cy.wrap({name: 'Jane'}).invoke('name') // Errors, 'name' is not a function
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} functionName** ***(String)***
|
||||
|
||||
Name of function to be invoked.
|
||||
|
||||
**{% fa fa-angle-right %} args...**
|
||||
|
||||
Additional arguments to be given to the function call. There is no limit to the number of arguments.
|
||||
|
||||
## Yields
|
||||
|
||||
`.invoke()` yields the return value of the invoked property.
|
||||
|
||||
## Timeout
|
||||
|
||||
# Examples
|
||||
|
||||
## Function
|
||||
|
||||
**Assert on a function's return value**
|
||||
|
||||
```javascript
|
||||
var fn = function(){
|
||||
return "bar"
|
||||
return 'bar'
|
||||
}
|
||||
|
||||
cy.wrap({foo: fn}).invoke("foo").should("eq", "bar") // true
|
||||
cy.wrap({foo: fn}).invoke('foo').should('eq', 'bar') // true
|
||||
```
|
||||
|
||||
{% note info Using cy.invoke('text') %}
|
||||
{% note info %}
|
||||
[Check out our example recipe where we use cy.invoke('text') to test against HTML content](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/bootstrapping_app_test_data_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
## Properties that are functions are invoked
|
||||
**Properties that are functions are invoked**
|
||||
|
||||
In the example below, we use `.invoke()` to force a hidden div to be `'display: block'` so we can interact with its children elements.
|
||||
|
||||
```javascript
|
||||
// force a hidden div to be 'display: block'
|
||||
// so we can interact with its children elements
|
||||
cy
|
||||
.get("div.container").should("be.hidden") // true
|
||||
cy.get('div.container').should('be.hidden') // true
|
||||
|
||||
.invoke("show") // call the jquery method 'show' on the 'div.container'
|
||||
.should("be.visible") // true
|
||||
.find("input").type("Cypress is great")
|
||||
.invoke('show') // call jquery method 'show' on the '.container'
|
||||
.should('be.visible') // true
|
||||
.find('input').type('Cypress is great')
|
||||
```
|
||||
|
||||
{% note info Using cy.invoke('show') and cy.invoke('trigger') %}
|
||||
{% note info %}
|
||||
[Check out our example recipe where we use cy.invoke('show') and cy.invoke('trigger') to click an element that is only visible on hover](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/hover_hidden_elements.js)
|
||||
{% endnote %}
|
||||
|
||||
## Useful for 3rd party plugins
|
||||
## 3rd Party Plugins
|
||||
|
||||
**Using a Kendo DropDown**
|
||||
|
||||
Invoke functions available from 3rd party plugins included in your app.
|
||||
|
||||
```javascript
|
||||
// as a slightly verbose approach
|
||||
cy.get("input").invoke("getKendoDropDownList").then(function(dropDownList){
|
||||
// the return of $input.getKendoDropDownList() has now become the new subject
|
||||
|
||||
// whatever the select method returns becomes the next subject after this
|
||||
return dropDownList.select("apples")
|
||||
cy.get('input').invoke('getKendoDropDownList').then(function(dropDownList){
|
||||
// yields the return of $input.getKendoDropDownList()
|
||||
return dropDownList.select('apples')
|
||||
})
|
||||
```
|
||||
|
||||
## We can rewrite the previous example in a more terse way and add an assertion.
|
||||
We can rewrite the previous example in a more terse way and add an assertion.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("input")
|
||||
.invoke("getKendoDropDownList")
|
||||
.invoke("select", "apples")
|
||||
.its("val").should("match", /apples/)
|
||||
.get('input')
|
||||
.invoke('getKendoDropDownList')
|
||||
.invoke('select', 'apples')
|
||||
.its('val').should('match', /apples/)
|
||||
```
|
||||
|
||||
# Function with Arguments Usage
|
||||
## Function with Arguments
|
||||
|
||||
## Send specific arguments to the function
|
||||
**Send specific arguments to the function**
|
||||
|
||||
```javascript
|
||||
var fn = function(a, b, c){
|
||||
@@ -87,24 +119,24 @@ var fn = function(a, b, c){
|
||||
|
||||
cy
|
||||
.wrap({sum: fn})
|
||||
.invoke("sum", 2, 4, 6)
|
||||
.should("be.gt", 10) // true
|
||||
.and("be.lt", 20) // true
|
||||
.invoke('sum', 2, 4, 6)
|
||||
.should('be.gt', 10) // true
|
||||
.and('be.lt', 20) // true
|
||||
```
|
||||
|
||||
{% note info Using cy.invoke('removeAttr', 'target') %}
|
||||
{% note info %}
|
||||
[Check out our example recipe where we use cy.invoke('removeAttr', 'target') to test clicking on a link without opening in a new tab](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/tab_handling_anchor_links_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
## Arguments are automatically forwarded to the function
|
||||
**Arguments are automatically forwarded to the function**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("img").invoke("attr", "src")
|
||||
.should("include", "myLogo")
|
||||
.get('img').invoke('attr', 'src')
|
||||
.should('include', 'myLogo')
|
||||
```
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [its](https://on.cypress.io/api/its)
|
||||
- [wrap](https://on.cypress.io/api/wrap)
|
||||
|
||||
@@ -4,40 +4,92 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
`cy.its` gets regular properties on the current subject.
|
||||
Get a property on the previously yielded subject.
|
||||
|
||||
If you want to call a function on the current subject, use [`cy.invoke`](https://on.cypress.io/api/invoke).
|
||||
{% note info %}
|
||||
If you want to call a function on the previously yielded subject, use [`cy.invoke`](https://on.cypress.io/api/invoke).
|
||||
{% endnote %}
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the value of the property |
|
||||
| **Timeout** | `cy.its` cannot timeout unless you've added assertions. The assertions will retry for the duration of [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
|
||||
# [cy.its( *propertyName* )](#usage)
|
||||
|
||||
Gets the property with the specified name.
|
||||
|
||||
You can also access multiple nested properties with **dot notation**.
|
||||
|
||||
# Usage
|
||||
|
||||
## Access properties
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
cy.wrap({foo: "bar"}).its("foo").should("eq", "bar") // true
|
||||
.its(propertyName)
|
||||
```
|
||||
|
||||
Call the `length` property on the current subject
|
||||
## Usage
|
||||
|
||||
`.its()` requires being chained off another cy command that *yields* an object with properties.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.wrap({width: '50'}).its('width') // Get the 'width' property
|
||||
cy.location().its('href') // Get the 'href' property
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.its('window') // Errors, cannot be chained off 'cy'
|
||||
cy.clearCookies().its('length') // Errors, 'clearCookies' does not yield Object
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} propertyName** ***(String)***
|
||||
|
||||
Name of property or nested properties (with dot notation) to get.
|
||||
|
||||
## Yields
|
||||
|
||||
`.invoke()` yields the value of the property.
|
||||
|
||||
## Timeout
|
||||
|
||||
# Examples
|
||||
|
||||
## Plain Objects
|
||||
|
||||
**Get property**
|
||||
|
||||
```javascript
|
||||
cy.wrap({foo: 'bar'}).its('foo').should('eq', 'bar') // true
|
||||
```
|
||||
|
||||
## DOM Elements
|
||||
|
||||
**Get the `length` property of a DOM element**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("ul li") // this returns us the jquery object
|
||||
.its("length") // calls the 'length' property returning that value
|
||||
.should("be.gt", 2) // ensure this length is greater than 2
|
||||
.get('ul li') // this returns us the jquery object
|
||||
.its('length') // calls the 'length' property returning that value
|
||||
.should('be.gt', 2) // ensure this length is greater than 2
|
||||
})
|
||||
```
|
||||
|
||||
## Access functions
|
||||
## Strings
|
||||
|
||||
**Get `length` of title**
|
||||
|
||||
```javascript
|
||||
cy.title().its('length').should('eq', 24)
|
||||
```
|
||||
|
||||
|
||||
## Functions
|
||||
|
||||
**Get function property**
|
||||
|
||||
```javascript
|
||||
var fn = function(){
|
||||
return 'bar'
|
||||
}
|
||||
|
||||
cy.wrap({foo: fn}).its('foo').should('be.a', 'function')
|
||||
```
|
||||
|
||||
**Inspect function**
|
||||
|
||||
You can access functions to then drill into their own properties instead of invoking them.
|
||||
|
||||
@@ -59,35 +111,34 @@ window.Factory = Factory
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.window() // get the window object
|
||||
.its("Factory") // now we are on the Factory function
|
||||
.invoke("create", "arg") // and now we can invoke properties on it
|
||||
|
||||
.window() // yields window object
|
||||
.its('Factory') // yields Factory function
|
||||
.invoke('create', 'arg') // now invoke properties on it
|
||||
```
|
||||
|
||||
{% note info Testing cy.window().its('fetch') %}
|
||||
[Check out our example recipe on testing window.fetch using cy.its()](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/spy_stub_clock_spec.js)
|
||||
{% note info %}
|
||||
[Check out our example recipe on testing `window.fetch` using `.its()`](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/spy_stub_clock_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
## Drill into nested properties
|
||||
## Nested Properties
|
||||
|
||||
You can additionally automatically drill into nested properties by using **dot notation**.
|
||||
You can drill into nested properties by using **dot notation**.
|
||||
|
||||
```javascript
|
||||
var obj = {
|
||||
foo: {
|
||||
bar: {
|
||||
baz: "quux"
|
||||
var user = {
|
||||
contacts: {
|
||||
work: {
|
||||
name: 'Kamil'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cy.wrap(obj).its("foo.bar.baz").should("eq", "quux") // true
|
||||
cy.wrap(user).its('contacts.work.name').should('eq', 'Kamil') // true
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Fetch 'comments' fixture
|
||||
**Get `responseBody` of aliased route**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
@@ -110,7 +161,7 @@ When clicking on `its` within the command log, the console outputs the following
|
||||
|
||||

|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [invoke](https://on.cypress.io/api/invoke)
|
||||
- [wrap](https://on.cypress.io/api/wrap)
|
||||
|
||||
@@ -6,29 +6,54 @@ description: ''
|
||||
|
||||
Get the last DOM element within a set of DOM elements.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.last` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.last()](#usage)
|
||||
```javascript
|
||||
.last()
|
||||
.last(options)
|
||||
```
|
||||
|
||||
Reduce the set of matched DOM elements to the final one in the set.
|
||||
## Usage
|
||||
|
||||
# Options
|
||||
`.last()` requires being chained off another cy command that *yields* a DOM element or set of DOM elements.
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.last`.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
**cy.last( *options* )**
|
||||
```javascript
|
||||
cy.get('nav a').last() // Yield last link in nav
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.last() // Errors, cannot be chained off 'cy'
|
||||
cy.getCookies().last() // Errors, 'getCookies' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.last`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Get the last list item in a list.
|
||||
`.last()` yields the new DOM element found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.last()` will continue to look for the last element for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Last element
|
||||
|
||||
**Get the last list item in a list.**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -41,15 +66,15 @@ Option | Default | Notes
|
||||
|
||||
```javascript
|
||||
// returns <li class="four">Knick knack on my door</li>
|
||||
cy.get("ul").last()
|
||||
cy.get('ul').last()
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Find the last button in the form
|
||||
**Find the last button in the form**
|
||||
|
||||
```javascript
|
||||
cy.get("form").find("button").last()
|
||||
cy.get('form').find('button').last()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -60,6 +85,6 @@ When clicking on `last` within the command log, the console outputs the followin
|
||||
|
||||
<img width="746" alt="screen shot 2015-11-29 at 12 34 07 pm" src="https://cloud.githubusercontent.com/assets/1271364/11458799/91a115cc-9695-11e5-8569-93fbaa2704d4.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [first](https://on.cypress.io/api/first)
|
||||
|
||||
@@ -4,105 +4,139 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the remote `window.location` as a normalized object.
|
||||
Get the remote `window.location` as an object.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | location object detailed below |
|
||||
| **Timeout** | *cannot timeout* |
|
||||
# Syntax
|
||||
|
||||
# [cy.location()](#usage)
|
||||
```javascript
|
||||
.location()
|
||||
.location(key)
|
||||
.location(options)
|
||||
.location(key, options)
|
||||
```
|
||||
|
||||
Given a remote URL of `http://localhost:8000/app/index.html?q=dan#/users/123/edit`, an object would be returned with the following properties:
|
||||
## Usage
|
||||
|
||||
Key | Type | Returns
|
||||
--- | --- | ----
|
||||
`hash` | string | #/users/123/edit
|
||||
`host` | string | localhost:8000
|
||||
`hostname` | string | localhost
|
||||
`href` | string | http://localhost:8000/app/index.html?q=brian#/users/123/edit
|
||||
`origin` | string | http://localhost:8000
|
||||
`pathname` | string | /app.index.html
|
||||
`port` | string | 8000
|
||||
`protocol` | string | http:
|
||||
`search` | string | ?q=brian
|
||||
`toString` | function | http://localhost:8000/app/index.html?q=brian#/users/123/edit
|
||||
`cy.location()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
# [cy.location( *key* )](#key-usage)
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
Get the specific value by key of the location object above.
|
||||
```javascript
|
||||
cy.location()
|
||||
```
|
||||
|
||||
# Options
|
||||
## Arguments
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.location`.
|
||||
**{% fa fa-angle-right %} key** ***(String)***
|
||||
|
||||
**cy.location( *options* )**
|
||||
**cy.location( *key*, *options* )**
|
||||
A key on the location object.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.location()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Check location for query params and pathname
|
||||
`.location()` yields the location object with the following properties:
|
||||
|
||||
- `hash`
|
||||
- `host`
|
||||
- `hostname`
|
||||
- `href`
|
||||
- `origin`
|
||||
- `pathname`
|
||||
- `port`
|
||||
- `protocol`
|
||||
- `search`
|
||||
- `toString`
|
||||
|
||||
## Timeout
|
||||
|
||||
# Examples
|
||||
|
||||
## Location Properties
|
||||
|
||||
**Make assertions about every location property**
|
||||
|
||||
```javascript
|
||||
cy.visit('http://localhost:8000/app/index.html?q=dan#/users/123/edit')
|
||||
|
||||
cy.location().should(function(location) {
|
||||
expect(location.hash).to.eq('#/users/123/edit')
|
||||
expect(location.host).to.eq('localhost:8000')
|
||||
expect(location.hostname).to.eq('localhost')
|
||||
expect(location.href).to.eq('http://localhost:8000/app/index.html?q=dan#/users/123/edit')
|
||||
expect(location.origin).to.eq('http://localhost:8000')
|
||||
expect(location.pathname).to.eq('/app.index.html')
|
||||
expect(location.port).to.eq('8000')
|
||||
expect(location.protocol).to.eq('http:')
|
||||
expect(location.search).to.eq('?q=dan')
|
||||
expect(location.toString()).to.eq('http://localhost:8000/app/index.html?q=brian#/users/123/edit')
|
||||
})
|
||||
```
|
||||
|
||||
**Check location for query params and pathname**
|
||||
|
||||
```javascript
|
||||
// we can yield the location subject and work with
|
||||
// it directly as an object
|
||||
cy
|
||||
.get("#search").type("brian{enter}")
|
||||
.location().should(function(location){
|
||||
expect(location.search).to.eq("?search=brian")
|
||||
expect(location.pathname).to.eq("/users")
|
||||
expect(location.toString()).to.eq("http://localhost:8000/users?search=brian")
|
||||
})
|
||||
cy.get('#search').type('niklas{enter}')
|
||||
cy.location().should(function(location){
|
||||
expect(location.search).to.eq('?search=niklas')
|
||||
expect(location.pathname).to.eq('/users')
|
||||
})
|
||||
```
|
||||
|
||||
# Key Usage
|
||||
## Key
|
||||
|
||||
## Assert that a redirect works
|
||||
**Assert that a redirect works**
|
||||
|
||||
```javascript
|
||||
// we should be redirected to the login page
|
||||
cy
|
||||
.visit("http://localhost:3000/admin")
|
||||
.location("pathname").should("eq", "/login")
|
||||
.visit('http://localhost:3000/admin')
|
||||
.location('pathname').should('eq', '/login')
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
## Do not use `window.location`
|
||||
**No need to use `window.location`**
|
||||
|
||||
Let's examine the following scenario:
|
||||
Cypress automatically normalizes the `.location()` command and strips out extraneous values and properties found in `window.location`. Also, the object literal yielded by `.location()` is just a basic object literal, not the special `window.location` object.
|
||||
|
||||
When changing properties on the real `window.location` object, it forces the browser to navigate away. In Cypress, the object yielded is a plain object, so changing its properties will have no effect on navigation.
|
||||
|
||||
***Console output of `window.location`***
|
||||
|
||||
```javascript
|
||||
// get our remote window and log out
|
||||
// the window.location object
|
||||
cy.window().then(function(window){
|
||||
console.log(window.location)
|
||||
})
|
||||
```
|
||||
|
||||
<img width="422" alt="screen shot 2017-05-26 at 11 41 27 am" src="https://cloud.githubusercontent.com/assets/1271364/26501744/6f9b6188-4208-11e7-91ce-59dbb455b1fc.png">
|
||||
|
||||
***Console output of `.location()`***
|
||||
|
||||
```javascript
|
||||
// go through the location command
|
||||
// and log out this object
|
||||
cy.location().then(function(location){
|
||||
console.log(location)
|
||||
})
|
||||
```
|
||||
|
||||
Cypress automatically normalizes the `cy.location()` command and strips out extrenuous values and properties found in `window.location`. Also the object literal returned by `cy.location()` is just a basic object literal, not the special `window.location` object.
|
||||
<img width="478" alt="screen shot 2017-05-26 at 11 42 11 am" src="https://cloud.githubusercontent.com/assets/1271364/26501743/6f8fcb84-4208-11e7-9f08-9c97592afc08.png">
|
||||
|
||||
When changing properties on the real `window.location` object, it will force the browser to navigate away. In Cypress, the object we returned is a plain object, and changing or affecting its properties will have no effect on navigation.
|
||||
|
||||
# Command Log
|
||||
|
||||
## Assert on the location's href
|
||||
**Assert on the location's href**
|
||||
|
||||
```javascript
|
||||
cy.location().should(function(location){
|
||||
expect(location.href).to.include("commands/querying")
|
||||
expect(location.href).to.include('commands/querying')
|
||||
})
|
||||
```
|
||||
|
||||
@@ -114,7 +148,8 @@ When clicking on `location` within the command log, the console outputs the foll
|
||||
|
||||

|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [hash](https://on.cypress.io/api/hash)
|
||||
- [url](https://on.cypress.io/api/url)
|
||||
- [window](https://on.cypress.io/api/window)
|
||||
|
||||
@@ -4,46 +4,71 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Print a message to the Command Log within Cypress.
|
||||
Print a message to the Cypress Command Log.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | null |
|
||||
| **Timeout** | *cannot timeout* |
|
||||
|
||||
# [cy.log( *message* )](#usage)
|
||||
|
||||
Print the message to the Command Log.
|
||||
|
||||
# [cy.log( *message*, *arguments* )](#arguments-usage)
|
||||
|
||||
Print the message to the Command Log, along with any arguments.
|
||||
|
||||
# Usage
|
||||
|
||||
## Log a message to the Command Log.
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
cy.log("Login successful")
|
||||
.log(message)
|
||||
.log(message, args...)
|
||||
```
|
||||
|
||||
# Arguments Usage
|
||||
## Usage
|
||||
|
||||
## Log a message with arguments to the Command Log.
|
||||
`.log()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
// print previously saved variable 'events' to the Command Log.
|
||||
cy.log("events triggered", events)
|
||||
cy.log('created new user')
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} message** ***(String)***
|
||||
|
||||
Message to be printed to Cypress Command Log.
|
||||
|
||||
**{% fa fa-angle-right %} args...**
|
||||
|
||||
Additional arguments to be printed to the Cypress Command Log. There is no limit to the number of arguments.
|
||||
|
||||
|
||||
## Yields
|
||||
|
||||
`.log()` yields `null`.
|
||||
|
||||
## Timeout
|
||||
|
||||
|
||||
# Examples
|
||||
|
||||
## Message
|
||||
|
||||
**Print a message to the Command Log.**
|
||||
|
||||
```javascript
|
||||
cy.click('Login')
|
||||
cy.url().should('not.include', 'login')
|
||||
cy.log('Login successful')
|
||||
```
|
||||
|
||||
# Arguments
|
||||
|
||||
**Print a message with arguments to the Command Log.**
|
||||
|
||||
```javascript
|
||||
cy.log('events triggered', events)
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Print messages with arguments to the Command Log.
|
||||
**Print messages with arguments to the Command Log.**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.log("log out any message we want here")
|
||||
.log("another message", ["one", "two", "three"])
|
||||
.log('log out any message we want here')
|
||||
.log('another message', ['one', 'two', 'three'])
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -53,3 +78,7 @@ The commands above will display in the command log as:
|
||||
When clicking on `log` within the command log, the console outputs the following:
|
||||
|
||||
<img width="746" alt="console display of cy.log" src="https://cloud.githubusercontent.com/assets/1271364/21321324/4f616dec-c5e2-11e6-8c2f-924e7bfd6f87.png">
|
||||
|
||||
# See also
|
||||
|
||||
- [exec](https://on.cypress.io/api/exec)
|
||||
|
||||
@@ -4,36 +4,62 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the immediately following sibling of each DOM element in the set of matched DOM elements.
|
||||
Get the immediately following sibling of each DOM element within a set of DOM elements.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.next` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.next()](#usage)
|
||||
```javascript
|
||||
.next()
|
||||
.next(selector)
|
||||
.next(options)
|
||||
.next(selector, options)
|
||||
```
|
||||
|
||||
Get the next sibling of the elements.
|
||||
## Usage
|
||||
|
||||
# [cy.next( *selector* )](#selector-usage)
|
||||
`.next()` requires being chained off another cy command that *yields* a DOM element or set of DOM elements.
|
||||
|
||||
When a selector is provided, it retrieves the next sibling only if it matches that selector.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# Options
|
||||
```javascript
|
||||
cy.get('nav a:first').next() // Yield next link in nav
|
||||
```
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.next`.
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
**cy.next( *options* )**
|
||||
**cy.next( *selector*, *options* )**
|
||||
```javascript
|
||||
cy.next() // Errors, cannot be chained off 'cy'
|
||||
cy.getCookies().next() // Errors, 'getCookies' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
A selector used to filter matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.next()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Find the element next to `.second`
|
||||
`.next()` yields the new DOM element(s) found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.next()` will continue to look for the next element for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Next
|
||||
|
||||
**Find the element next to `.second`**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -44,13 +70,13 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
//returns <li>bananas</li>
|
||||
cy.get(".second").next()
|
||||
// yields <li>bananas</li>
|
||||
cy.get('.second').next()
|
||||
```
|
||||
|
||||
# Selector Usage
|
||||
## Selector
|
||||
|
||||
## Find the very next sibling of each li. Keep only the ones with a class `selected`.
|
||||
**Find the very next sibling of each li. Keep only the ones with a class `selected`.**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -62,16 +88,16 @@ cy.get(".second").next()
|
||||
```
|
||||
|
||||
```javascript
|
||||
//returns <li>pineapples</li>
|
||||
cy.get("li").next(".selected")
|
||||
// yields <li>pineapples</li>
|
||||
cy.get('li').next('.selected')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Find the element next to the active li
|
||||
**Find the element next to the `.active` li**
|
||||
|
||||
```javascript
|
||||
cy.get(".left-nav").find("li.active").next()
|
||||
cy.get('.left-nav').find('li.active').next()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -82,6 +108,8 @@ When clicking on `next` within the command log, the console outputs the followin
|
||||
|
||||
<img width="547" alt="screen shot 2015-11-29 at 12 42 22 pm" src="https://cloud.githubusercontent.com/assets/1271364/11458858/b30b0a0a-9696-11e5-99b9-d785b597287c.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [nextAll](https://on.cypress.io/api/nextAll)
|
||||
- [nextUntil](https://on.cypress.io/api/nextUntil)
|
||||
- [prev](https://on.cypress.io/api/prev)
|
||||
|
||||
@@ -4,36 +4,62 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get all following siblings of each DOM element in the set of matched DOM elements.
|
||||
Get all following siblings of each DOM element in a set of matched DOM elements.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.nextAll` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.nextAll()](#usage)
|
||||
```javascript
|
||||
.nextAll()
|
||||
.nextAll(selector)
|
||||
.nextAll(options)
|
||||
.nextAll(selector, options)
|
||||
```
|
||||
|
||||
Get all of the next siblings of the elements.
|
||||
## Usage
|
||||
|
||||
# [cy.nextAll( *selector* )](#selector-usage)
|
||||
`.nextAll()` requires being chained off another cy command that *yields* a DOM element or set of DOM elements.
|
||||
|
||||
When a selector is provided, it retrieves all of the following siblings only if it matches that selector.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# Options
|
||||
```javascript
|
||||
cy.get('.active').nextAll() // Yield all links next to `.active`
|
||||
```
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.nextAll`.
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
**cy.nextAll( *options* )**
|
||||
**cy.nextAll( *selector*, *options* )**
|
||||
```javascript
|
||||
cy.nextAll() // Errors, cannot be chained off 'cy'
|
||||
cy.getCookies().nextAll() // Errors, 'getCookies' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
A selector used to filter matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.nextAll()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Find all of the element's siblings following `.second`
|
||||
`.nextAll()` yields the new DOM elements found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.nextAll()` will continue to look for all next element(s) for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## All Next
|
||||
|
||||
**Find all of the element's siblings following `.second`**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -46,13 +72,13 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
//returns [<li>bananas</li>, <li>pineapples</li>, <li>grapes</li>]
|
||||
cy.get(".second").nextAll()
|
||||
// yields [<li>bananas</li>, <li>pineapples</li>, <li>grapes</li>]
|
||||
cy.get('.second').nextAll()
|
||||
```
|
||||
|
||||
# Selector Usage
|
||||
## Selector
|
||||
|
||||
## Find all of the following siblings of each li. Keep only the ones with a class `selected`.
|
||||
**Find all of the following siblings of each li. Keep only the ones with a class `selected`.**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -65,16 +91,16 @@ cy.get(".second").nextAll()
|
||||
```
|
||||
|
||||
```javascript
|
||||
//returns <li>pineapples</li>
|
||||
cy.get("li").nextAll(".selected")
|
||||
// yields <li>pineapples</li>
|
||||
cy.get('li').nextAll('.selected')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Find all elements following the active li
|
||||
**Find all elements following the `.active` li**
|
||||
|
||||
```javascript
|
||||
cy.get(".left-nav").find("li.active").nextAll()
|
||||
cy.get('.left-nav').find('li.active').nextAll()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -85,7 +111,7 @@ When clicking on `nextAll` within the command log, the console outputs the follo
|
||||
|
||||
<img width="567" alt="screen shot 2017-03-23 at 2 05 52 pm" src="https://cloud.githubusercontent.com/assets/1271364/24262907/f2b7fe78-0fd1-11e7-921c-6eabf6e32abb.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [next](https://on.cypress.io/api/next)
|
||||
- [nextUntil](https://on.cypress.io/api/nextuntil)
|
||||
|
||||
@@ -4,46 +4,73 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get all following siblings of each DOM element in the set of matched DOM elements up to, but not including, the element matched by the selector
|
||||
Get all following siblings of each DOM element in a set of matched DOM elements up to, but not including, the element provided.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.nextUntil` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
|
||||
# [cy.nextUntil( *selector* )](#usage)
|
||||
# Syntax
|
||||
|
||||
Get all of the next siblings of the elements until the selector.
|
||||
```javascript
|
||||
.nextUntil(selector)
|
||||
.nextUntil(selector, filter)
|
||||
.nextUntil(selector, filter, options)
|
||||
.nextUntil(element)
|
||||
.nextUntil(element, filter)
|
||||
.nextUntil(element, filter, options)
|
||||
```
|
||||
|
||||
# [cy.nextUntil( *selector*, *filter )](#filter-usage)
|
||||
## Usage
|
||||
|
||||
When a filter is provided, it retrieves all of the following siblings up until the selector only if it matches that filter.
|
||||
`.nextUntil()` requires being chained off another cy command that *yields* a DOM element or set of DOM elements.
|
||||
|
||||
# [cy.nextUntil( *element* )](#element-usage)
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
Get all of the next siblings of the elements until the DOM node or jQuery object.
|
||||
```javascript
|
||||
cy.get('div').nextUntil('.warning') // Yield siblings after 'div' until '.warning'
|
||||
```
|
||||
|
||||
# [cy.nextUntil( *element*, *filter )](#element-filter-usage)
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
When a filter is provided, it retrieves all of the following siblings up until the DOM node or jQuery object only if it matches that filter.
|
||||
```javascript
|
||||
cy.nextUntil() // Errors, cannot be chained off 'cy'
|
||||
cy.location().nextUntil('path') // Errors, 'location' does not yield DOM element
|
||||
```
|
||||
|
||||
# Options
|
||||
## Arguments
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.nextUntil`.
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
**cy.nextUntil( *selector*, *options* )**
|
||||
**cy.nextUntil( *selector*, *filter*, *options* )**
|
||||
**cy.nextUntil( *element*, *options* )**
|
||||
**cy.nextUntil( *element*, *filter*, *options* )**
|
||||
The selector where you want finding next siblings to stop.
|
||||
|
||||
**{% fa fa-angle-right %} element** ***(DOM node, jQuery Object)***
|
||||
|
||||
The element where you want finding next siblings to stop.
|
||||
|
||||
**{% fa fa-angle-right %} filter** ***(String selector)***
|
||||
|
||||
A selector used to filter matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.nextUntil()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element(s)
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Find all of the element's siblings following `#veggies` until `#nuts`
|
||||
`.nextUntil()` yields the new DOM element(s) found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.nextUntil()` will continue to look for the next element(s) for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Selector
|
||||
|
||||
**Find all of the element's siblings following `#veggies` until `#nuts`**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -64,15 +91,15 @@ Option | Default | Notes
|
||||
|
||||
```javascript
|
||||
//returns [<li>cucumbers</li>, <li>carrots</li>, <li>corn</li>]
|
||||
cy.get("#veggies").nextUntil("#nuts")
|
||||
cy.get('#veggies').nextUntil('#nuts')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Find all of the element's siblings following `#veggies` until `#nuts`
|
||||
**Find all of the element's siblings following `#veggies` until `#nuts`**
|
||||
|
||||
```javascript
|
||||
cy.get("#veggies").nextUntil("#nuts")
|
||||
cy.get('#veggies').nextUntil('#nuts')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -83,8 +110,9 @@ When clicking on `nextUntil` within the command log, the console outputs the fol
|
||||
|
||||
<img width="514" alt="screen shot 2017-03-23 at 2 18 01 pm" src="https://cloud.githubusercontent.com/assets/1271364/24263481/a20ce2f2-0fd3-11e7-881c-f6bf8d652263.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [next](https://on.cypress.io/api/next)
|
||||
- [nextAll](https://on.cypress.io/api/nextall)
|
||||
- [parentsUntil](https://on.cypress.io/api/parentsuntil)
|
||||
- [prevUntil](https://on.cypress.io/api/prevuntil)
|
||||
|
||||
@@ -4,42 +4,77 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Remove DOM elements from the set of DOM elements. Opposite of [`cy.filter()`](https://on.cypress.io/api/filter)
|
||||
Filter DOM element(s) from a set of DOM elements.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.not` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
{% note info %}
|
||||
Opposite of [`.filter()`](https://on.cypress.io/api/filter)
|
||||
{% endnote %}
|
||||
|
||||
# [cy.not( *selector* )](#selector-usage)
|
||||
# Syntax
|
||||
|
||||
Remove the element(s) by it's selector from the elements
|
||||
```javascript
|
||||
.not(selector)
|
||||
.not(selector, options)
|
||||
```
|
||||
|
||||
# Options
|
||||
## Usage
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.not`.
|
||||
`.not()` requires being chained off another cy command that *yields* a DOM element or DOM elements.
|
||||
|
||||
**cy.not( *selector*, *options* )**
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.get('input').not('.required') // Yield all inputs without class '.required'
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.not('.icon') // Errors, cannot be chained off 'cy'
|
||||
cy.location().not() // Errors, 'location' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
A selector used to remove matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.not()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
|
||||
# Selector Usage
|
||||
## Yields
|
||||
|
||||
## Filter the current subject to the elements that do not have class `active`.
|
||||
`.filter()` yields the new DOM element(s) without the selector provided in the command's argument.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.filter()` will continue to look for the element(s) for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Selector
|
||||
|
||||
**Yield the elements that do not have class `active`.**
|
||||
|
||||
```javascript
|
||||
cy.get(".left-nav>.nav").find(">li").not(".active")
|
||||
cy.get('.left-nav>.nav')
|
||||
.find('>li').not('.active')
|
||||
.should('not.have.class', 'active') // true
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Find all buttons that are not of type submit
|
||||
**Find all buttons that are not of type submit**
|
||||
|
||||
```javascript
|
||||
cy.get("form").find("button").not("[type='submit']")
|
||||
cy.get('form').find('button').not('[type="submit"]')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -50,6 +85,6 @@ When clicking on `not` within the command log, the console outputs the following
|
||||
|
||||
<img width="689" alt="screen shot 2015-11-29 at 12 37 39 pm" src="https://cloud.githubusercontent.com/assets/1271364/11458819/0d6870f6-9696-11e5-9364-2685b8ffc71b.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [filter](https://on.cypress.io/api/filter)
|
||||
|
||||
@@ -4,55 +4,81 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the parent DOM element of the DOM elements.
|
||||
Get the parent DOM element of a set of DOM elements.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.parent` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.parent()](#usage)
|
||||
```javascript
|
||||
.parent()
|
||||
.parent(selector)
|
||||
.parent(options)
|
||||
.parent(selector, options)
|
||||
```
|
||||
|
||||
Get the parent of each element in the current set of matched elements.
|
||||
## Usage
|
||||
|
||||
# [cy.parent( *selector* )](#selector-usage)
|
||||
`.parent()` requires being chained off another cy command that *yields* a DOM element or set of DOM elements.
|
||||
|
||||
Get the parent of each element in the current set of matched elements filtered by selector.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# Options
|
||||
```javascript
|
||||
cy.get('header').parent() // Yield parent el of `header`
|
||||
```
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.parent`.
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
**cy.parent( *options* )**
|
||||
**cy.parent( *selector*, *options* )**
|
||||
```javascript
|
||||
cy.parent() // Errors, cannot be chained off 'cy'
|
||||
cy.reload().parent() // Errors, 'reload' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
A selector used to filter matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.parent()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Get the parent of the active `li`
|
||||
`.parent()` yields the new DOM element(s) found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.parent()` will continue to look for the parent element(s) for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Parent
|
||||
|
||||
**Get the parent of the active `li`**
|
||||
|
||||
```javascript
|
||||
cy.get("li.active").parent()
|
||||
cy.get('li.active').parent()
|
||||
```
|
||||
|
||||
# Selector Usage
|
||||
## Selector
|
||||
|
||||
## Get the parent with class `nav` of the active `li`
|
||||
**Get the parent with class `nav` of the active `li`**
|
||||
|
||||
```javascript
|
||||
cy.get("li.active").parent(".nav")
|
||||
cy.get('li.active').parent('.nav')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Assert on the parent of the active li
|
||||
**Assert on the parent of the active li**
|
||||
|
||||
```javascript
|
||||
cy.get("li.active").parent().should("have.class", "nav")
|
||||
cy.get('li.active').parent().should('have.class', 'nav')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -63,7 +89,8 @@ When clicking on the `parent` command within the command log, the console output
|
||||
|
||||
<img width="440" alt="screen shot 2015-11-27 at 1 58 44 pm" src="https://cloud.githubusercontent.com/assets/1271364/11447130/11b22c02-950f-11e5-9b82-cc3b2ff8548e.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [parents](https://on.cypress.io/api/parents)
|
||||
- [children](https://on.cypress.io/api/children)
|
||||
- [parents](https://on.cypress.io/api/parents)
|
||||
- [parentsUntil](https://on.cypress.io/api/parentsuntil)
|
||||
|
||||
@@ -4,55 +4,83 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the parents DOM elements of the DOM elements.
|
||||
Get the parent DOM elements of a set of DOM elements.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.parents` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
|
||||
# [cy.parents()](#usage)
|
||||
# Syntax
|
||||
|
||||
Get the ancestors of each element in the current set of matched elements.
|
||||
```javascript
|
||||
.parents()
|
||||
.parents(selector)
|
||||
.parents(options)
|
||||
.parents(selector, options)
|
||||
```
|
||||
|
||||
# [cy.parents( *selector* )](#selector-usage)
|
||||
## Usage
|
||||
|
||||
Get the ancestors of each element in the current set of matched elements filtered by selector
|
||||
`.parents()` requires being chained off another cy command that *yields* a DOM element or set of DOM elements.
|
||||
|
||||
# Options
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.parents`.
|
||||
```javascript
|
||||
cy.get('aside').parents() // Yield parents of aside
|
||||
```
|
||||
|
||||
**cy.parents( *options* )**
|
||||
**cy.parents( *selector*, *options* )**
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.parents() // Errors, cannot be chained off 'cy'
|
||||
cy.go('back').parents() // Errors, 'go' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
A selector used to filter matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.parents()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the elements
|
||||
|
||||
# Usage
|
||||
|
||||
## Get the parents of the active `li`
|
||||
## Yields
|
||||
|
||||
`.parents()` yields the new DOM element(s) found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.parents()` will continue to look for the next element(s) for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Parents
|
||||
|
||||
**Get the parents of the active `li`**
|
||||
|
||||
```javascript
|
||||
cy.get("li.active").parents()
|
||||
cy.get('li.active').parents()
|
||||
```
|
||||
|
||||
# Selector Usage
|
||||
## Selector
|
||||
|
||||
## Get the parents with class `nav` of the active `li`
|
||||
**Get the parents with class `nav` of the active `li`**
|
||||
|
||||
```javascript
|
||||
cy.get("li.active").parents(".nav")
|
||||
cy.get('li.active').parents('.nav')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Get the parents of the active `li`
|
||||
**Get the parents of the active `li`**
|
||||
|
||||
```javascript
|
||||
cy.get("li.active").parents()
|
||||
cy.get('li.active').parents()
|
||||
```
|
||||
|
||||
<img width="531" alt="screen shot 2015-11-27 at 2 02 59 pm" src="https://cloud.githubusercontent.com/assets/1271364/11447168/be286244-950f-11e5-82e8-9a2a6d1d08e8.png">
|
||||
@@ -61,7 +89,8 @@ When clicking on the `parents` command within the command log, the console outpu
|
||||
|
||||
<img width="537" alt="screen shot 2015-11-27 at 2 03 32 pm" src="https://cloud.githubusercontent.com/assets/1271364/11447171/c1ba5ef8-950f-11e5-9f2d-7fbd0b142649.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [parent](https://on.cypress.io/api/parent)
|
||||
- [children](https://on.cypress.io/api/children)
|
||||
- [parent](https://on.cypress.io/api/parent)
|
||||
- [parentsUntil](https://on.cypress.io/api/parentsuntil)
|
||||
|
||||
@@ -4,46 +4,72 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get all ancestors of each DOM element in the set of matched DOM elements up to, but not including, the element matched by the selector
|
||||
Get all ancestors of each DOM element in a set of matched DOM elements up to, but not including, the element provided.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.parentsUntil` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.parentsUntil( *selector* )](#usage)
|
||||
```javascript
|
||||
.parentUntil(selector)
|
||||
.parentUntil(selector, filter)
|
||||
.parentUntil(selector, filter, options)
|
||||
.parentUntil(element)
|
||||
.parentUntil(element, filter)
|
||||
.parentUntil(element, filter, options)
|
||||
```
|
||||
|
||||
Get all of the ancestors of the elements until the selector.
|
||||
## Usage
|
||||
|
||||
# [cy.parentsUntil( *selector*, *filter )](#filter-usage)
|
||||
`.parentsUntil()` requires being chained off another cy command that *yields* a DOM element or set of DOM elements.
|
||||
|
||||
When a filter is provided, it retrieves all of the ancestors up until the selector only if it matches that filter.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# [cy.parentsUntil( *element* )](#element-usage)
|
||||
```javascript
|
||||
cy.get('p').parentsUntil('.article') // Yield parents of 'p' until '.article'
|
||||
```
|
||||
|
||||
Get all of the ancestors of the elements until the DOM node or jQuery object.
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
# [cy.parentsUntil( *element*, *filter )](#element-filter-usage)
|
||||
```javascript
|
||||
cy.parentsUntil() // Errors, cannot be chained off 'cy'
|
||||
cy.location().parentsUntil('href') // Errors, 'location' does not yield DOM element
|
||||
```
|
||||
|
||||
When a filter is provided, it retrieves all of the ancestors up until the DOM node or jQuery object only if it matches that filter.
|
||||
## Arguments
|
||||
|
||||
# Options
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.parentsUntil`.
|
||||
The selector where you want finding parent ancestors to stop.
|
||||
|
||||
**cy.parentsUntil( *selector*, *options* )**
|
||||
**cy.parentsUntil( *selector*, *filter*, *options* )**
|
||||
**cy.parentsUntil( *element*, *options* )**
|
||||
**cy.parentsUntil( *element*, *filter*, *options* )**
|
||||
**{% fa fa-angle-right %} element** ***(DOM node, jQuery Object)***
|
||||
|
||||
The element where you want finding parent ancestors to stop.
|
||||
|
||||
**{% fa fa-angle-right %} filter** ***(String selector)***
|
||||
|
||||
A selector used to filter matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.parentsUntil()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element(s)
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Find all of the `.active` element's ancestors until `.nav`
|
||||
`.parentsUntil()` yields the new DOM element(s) found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.parentsUntil()` will continue to look for the parent element(s) for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Selector
|
||||
|
||||
**Find all of the `.active` element's ancestors until `.nav`**
|
||||
|
||||
```html
|
||||
<ul class="nav">
|
||||
@@ -62,16 +88,16 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
//returns [ul.menu, li]
|
||||
cy.get(".active").parentsUntil(".nav")
|
||||
// yields [ul.menu, li]
|
||||
cy.get('.active').parentsUntil('.nav')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Find all of the `.active` element's ancestors until `.nav`
|
||||
**Find all of the `.active` element's ancestors until `.nav`**
|
||||
|
||||
```javascript
|
||||
cy.get(".active").parentsUntil(".nav")
|
||||
cy.get('.active').parentsUntil('.nav')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -82,7 +108,7 @@ When clicking on `parentsUntil` within the command log, the console outputs the
|
||||
|
||||
<img width="523" alt="screen shot 2017-03-23 at 2 37 39 pm" src="https://cloud.githubusercontent.com/assets/1271364/24264309/60cc75de-0fd6-11e7-97b4-d0aa184b0ba6.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [parent](https://on.cypress.io/api/parent)
|
||||
- [parents](https://on.cypress.io/api/parents)
|
||||
|
||||
@@ -4,38 +4,103 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
`cy.pause` will stop command execution and allow you to interact with your app, resume commands when you're ready, or choose when to run the next command.
|
||||
Stop `cy` commands from running and allow interaction with the application under test. You can then "resume" running all commands or choose to step through the "next" commands from the Command Log.
|
||||
|
||||
This does not set a `debugger` in your code, unlike [`cy.debug`](https://on.cypress.io/api/debug)
|
||||
{% note info %}
|
||||
This does not set a `debugger` in your code, unlike [`.debug()`](https://on.cypress.io/api/debug)
|
||||
{% endnote %}
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the subject from the previous command for further chaining |
|
||||
| **Timeout** | *cannot timeout* |
|
||||
# Syntax
|
||||
|
||||
# [cy.pause()](#usage)
|
||||
```javascript
|
||||
.pause()
|
||||
.pause(options)
|
||||
```
|
||||
|
||||
Stop command execution at the current command.
|
||||
## Usage
|
||||
|
||||
# Options
|
||||
`.pause()` can be chained off of `cy` or any cy command.
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.pause`.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
**cy.pause(*options* )**
|
||||
```javascript
|
||||
cy.pause().getCookie('app') // Pause at the beginning of commands
|
||||
cy.get('nav').pause() // Pause after the `get` commands yield
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.pause()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
`.pause()` yields the previous command's yield.
|
||||
|
||||
## Timeout
|
||||
|
||||
# Examples
|
||||
|
||||
## Pause
|
||||
|
||||
**Pause after assertion**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("a").should("have.attr", "href").and("match", /dashboard/)
|
||||
.pause()
|
||||
.get("button").should("not.be.disabled")
|
||||
cy.get('a').should('have.attr', 'href').and('match', /dashboard/).pause()
|
||||
cy.get('button').should('not.be.disabled')
|
||||
```
|
||||
|
||||
# Related
|
||||
# Command Log
|
||||
|
||||
**Pause and step through each `.click()` command**
|
||||
|
||||
```javascript
|
||||
cy.get('#action-canvas')
|
||||
.click(80, 75)
|
||||
.pause()
|
||||
.click(170, 75)
|
||||
.click(80, 165)
|
||||
.click(100, 185)
|
||||
.click(125, 190)
|
||||
.click(150, 185)
|
||||
.click(170, 165)
|
||||
```
|
||||
|
||||
The commands above will display in the GUI as:
|
||||
|
||||
<img width="985" alt="screen shot 2017-05-26 at 2 18 10 pm" src="https://cloud.githubusercontent.com/assets/1271364/26507426/4d48a5e4-421e-11e7-9bd4-c6829f80910d.png">
|
||||
|
||||
When clicking on "Next: 'click'" at the top of the Command Log, the Command Log will run only the next command and pause again.
|
||||
|
||||
***Click "Next"***
|
||||
|
||||
<img width="985" alt="screen shot 2017-05-26 at 2 18 15 pm" src="https://cloud.githubusercontent.com/assets/1271364/26507427/4d49e33c-421e-11e7-9bea-26b89ec6fe32.png">
|
||||
|
||||
***Click "Next" again***
|
||||
|
||||
<img width="985" alt="screen shot 2017-05-26 at 2 18 24 pm" src="https://cloud.githubusercontent.com/assets/1271364/26507424/4d446204-421e-11e7-82a1-a5ce8b4bb4a9.png">
|
||||
|
||||
***Click "Next" again***
|
||||
|
||||
<img width="985" alt="screen shot 2017-05-26 at 2 18 29 pm" src="https://cloud.githubusercontent.com/assets/1271364/26507421/4d3a69e8-421e-11e7-9a26-1026d0d133ec.png">
|
||||
|
||||
***Click "Next" again***
|
||||
|
||||
<img width="985" alt="screen shot 2017-05-26 at 2 18 33 pm" src="https://cloud.githubusercontent.com/assets/1271364/26507422/4d3b30a8-421e-11e7-940d-bd7bdc7b6e81.png">
|
||||
|
||||
***Click "Next" again***
|
||||
|
||||
<img width="985" alt="screen shot 2017-05-26 at 2 18 36 pm" src="https://cloud.githubusercontent.com/assets/1271364/26507420/4d37dcc8-421e-11e7-8428-8529ad628b05.png">
|
||||
|
||||
***Click "Next" again, then 'Resume'***
|
||||
|
||||
<img width="985" alt="screen shot 2017-05-26 at 2 18 51 pm" src="https://cloud.githubusercontent.com/assets/1271364/26507423/4d3c5992-421e-11e7-8df8-9af67f5ceb4a.png">
|
||||
|
||||
# See also
|
||||
|
||||
- [debug](https://on.cypress.io/api/debug)
|
||||
|
||||
@@ -4,36 +4,62 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the immediately preceding sibling of each element in the set of the elements.
|
||||
Get the immediately preceding sibling of each element in a set of the elements.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.prev` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.prev()](#usage)
|
||||
```javascript
|
||||
.prev()
|
||||
.prev(selector)
|
||||
.prev(options)
|
||||
.prev(selector, options)
|
||||
```
|
||||
|
||||
Get the immediately preceding sibling of each element in the set of matched elements.
|
||||
## Usage
|
||||
|
||||
# [cy.prev( *selector* )](#selector-usage)
|
||||
`.prev()` requires being chained off another cy command that *yields* a DOM element or set of DOM elements.
|
||||
|
||||
Get the immediately preceding sibling of each element in the set of matched elements filtered by selector.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# Options
|
||||
```javascript
|
||||
cy.get('tr.highlight').prev() // Yield previous 'tr'
|
||||
```
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.prev`.
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
**cy.prev( *options* )**
|
||||
**cy.prev( *selector*, *options* )**
|
||||
```javascript
|
||||
cy.prev() // Errors, cannot be chained off 'cy'
|
||||
cy.getCookies().prev() // Errors, 'getCookies' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
A selector used to filter matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.prev()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Find the previous element of the element with class of `active`
|
||||
`.prev()` yields the new DOM element(s) found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.prev()` will continue to look for the previous element for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Previous
|
||||
|
||||
**Find the previous element of the element with class of `active`**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -46,13 +72,13 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
// returns <li>Lorikeets</li>
|
||||
cy.get(".active").prev()
|
||||
// yields <li>Lorikeets</li>
|
||||
cy.get('.active').prev()
|
||||
```
|
||||
|
||||
# Selector Usage
|
||||
## Selector
|
||||
|
||||
## Find the previous element with a class of `active`
|
||||
**Find the previous element with a class of `active`**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -65,16 +91,16 @@ cy.get(".active").prev()
|
||||
```
|
||||
|
||||
```javascript
|
||||
// returns <li>Cockatoos</li>
|
||||
cy.get("li").prev(".active")
|
||||
// yields <li>Cockatoos</li>
|
||||
cy.get('li').prev('.active')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Find the previous element of the active `li`
|
||||
**Find the previous element of the active `li`**
|
||||
|
||||
```javascript
|
||||
cy.get(".left-nav").find("li.active").prev()
|
||||
cy.get('.left-nav').find('li.active').prev()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -85,6 +111,8 @@ When clicking on `prev` within the command log, the console outputs the followin
|
||||
|
||||
<img width="446" alt="screen shot 2015-11-29 at 12 47 09 pm" src="https://cloud.githubusercontent.com/assets/1271364/11458886/5e20c63c-9697-11e5-9167-1b81f96e1906.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
1. [next](https://on.cypress.io/api/next)
|
||||
- [next](https://on.cypress.io/api/next)
|
||||
- [prevAll](https://on.cypress.io/api/prevall)
|
||||
- [prevUntil](https://on.cypress.io/api/prevuntil)
|
||||
|
||||
@@ -4,36 +4,55 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get all previous siblings of each DOM element in the set of matched DOM elements.
|
||||
Get all previous siblings of each DOM element in a set of matched DOM elements.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.prevAll` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.prevAll()](#usage)
|
||||
```javascript
|
||||
.prevAll()
|
||||
.prevAll(selector)
|
||||
.prevAll(options)
|
||||
.prevAll(selector, options)
|
||||
```
|
||||
|
||||
Get all of the next siblings of the elements.
|
||||
## Usage
|
||||
|
||||
# [cy.prevAll( *selector* )](#selector-usage)
|
||||
`.prevAll()` requires being chained off another cy command that *yields* a DOM element or set of DOM elements.
|
||||
|
||||
When a selector is provided, it retrieves all of the previous siblings only if it matches that selector.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# Options
|
||||
```javascript
|
||||
cy.get('.active').prevAll() // Yield all links previous to `.active`
|
||||
```
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.prevAll`.
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
**cy.prevAll( *options* )**
|
||||
**cy.prevAll( *selector*, *options* )**
|
||||
```javascript
|
||||
cy.prevAll() // Errors, cannot be chained off 'cy'
|
||||
cy.getCookies().prevAll() // Errors, 'getCookies' does not yield DOM element
|
||||
```
|
||||
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
A selector used to filter matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.prevAll()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
|
||||
# Usage
|
||||
# Examples
|
||||
|
||||
## Find all of the element's siblings before `.third`
|
||||
## All Previous
|
||||
|
||||
**Find all of the element's siblings before `.third`**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -46,13 +65,13 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
//returns [<li>apples</li>, <li>oranges</li>]
|
||||
cy.get(".third").prevAll()
|
||||
// yields [<li>apples</li>, <li>oranges</li>]
|
||||
cy.get('.third').prevAll()
|
||||
```
|
||||
|
||||
# Selector Usage
|
||||
## Selector
|
||||
|
||||
## Find all of the previous siblings of each li. Keep only the ones with a class `selected`.
|
||||
**Find all of the previous siblings of each li. Keep only the ones with a class `selected`.**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -65,16 +84,16 @@ cy.get(".third").prevAll()
|
||||
```
|
||||
|
||||
```javascript
|
||||
//returns <li>pineapples</li>
|
||||
cy.get("li").prevAll(".selected")
|
||||
// yields <li>pineapples</li>
|
||||
cy.get('li').prevAll('.selected')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Find all elements before the active li
|
||||
**Find all elements before the `.active` li**
|
||||
|
||||
```javascript
|
||||
cy.get(".left-nav").find("li.active").prevAll()
|
||||
cy.get('.left-nav').find('li.active').prevAll()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -85,8 +104,9 @@ When clicking on `prevAll` within the command log, the console outputs the follo
|
||||
|
||||
<img width="539" alt="screen shot 2017-03-23 at 2 50 26 pm" src="https://cloud.githubusercontent.com/assets/1271364/24264898/2219d1a4-0fd8-11e7-9e8b-6b2d97166d6a.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [nextAll](https://on.cypress.io/api/nextall)
|
||||
- [parentsAll](https://on.cypress.io/api/parentsall)
|
||||
- [prev](https://on.cypress.io/api/prev)
|
||||
- [prevUntil](https://on.cypress.io/api/prevuntil)
|
||||
- [nextAll](https://on.cypress.io/api/nextall)
|
||||
|
||||
@@ -4,46 +4,72 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get all previous siblings of each DOM element in the set of matched DOM elements up to, but not including, the element matched by the selector
|
||||
Get all previous siblings of each DOM element in a set of matched DOM elements up to, but not including, the element provided.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.prevUntil` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.prevUntil( *selector* )](#usage)
|
||||
```javascript
|
||||
.prevUntil(selector)
|
||||
.prevUntil(selector, filter)
|
||||
.prevUntil(selector, filter, options)
|
||||
.prevUntil(element)
|
||||
.prevUntil(element, filter)
|
||||
.prevUntil(element, filter, options)
|
||||
```
|
||||
|
||||
Get all of the previous siblings of the elements until the selector.
|
||||
## Usage
|
||||
|
||||
# [cy.prevUntil( *selector*, *filter )](#filter-usage)
|
||||
`.prevUntil()` requires being chained off another cy command that *yields* a DOM element or set of DOM elements.
|
||||
|
||||
When a filter is provided, it retrieves all of the previous siblings up until the selector only if it matches that filter.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# [cy.prevUntil( *element* )](#element-usage)
|
||||
```javascript
|
||||
cy.get('p').prevUntil('.intro') // Yield siblings before 'p' until '.intro'
|
||||
```
|
||||
|
||||
Get all of the previous siblings of the elements until the DOM node or jQuery object.
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
# [cy.prevUntil( *element*, *filter )](#element-filter-usage)
|
||||
```javascript
|
||||
cy.prevUntil() // Errors, cannot be chained off 'cy'
|
||||
cy.location().prevUntil('path') // Errors, 'location' does not yield DOM element
|
||||
```
|
||||
|
||||
When a filter is provided, it retrieves all of the previous siblings up until the DOM node or jQuery object only if it matches that filter.
|
||||
## Arguments
|
||||
|
||||
# Options
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.prevUntil`.
|
||||
The selector where you want finding previous siblings to stop.
|
||||
|
||||
**cy.prevUntil( *selector*, *options* )**
|
||||
**cy.prevUntil( *selector*, *filter*, *options* )**
|
||||
**cy.prevUntil( *element*, *options* )**
|
||||
**cy.prevUntil( *element*, *filter*, *options* )**
|
||||
**{% fa fa-angle-right %} element** ***(DOM node, jQuery Object)***
|
||||
|
||||
The element where you want finding previous siblings to stop.
|
||||
|
||||
**{% fa fa-angle-right %} filter** ***(String selector)***
|
||||
|
||||
A selector used to filter matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.prevUntil()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element(s)
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Find all of the element's siblings before `#nuts` until `#veggies`
|
||||
`.prevUntil()` yields the new DOM element(s) found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.prevUntil()` will continue to look for the previous element(s) for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Selector
|
||||
|
||||
**Find all of the element's siblings before `#nuts` until `#veggies`**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -63,16 +89,16 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
//returns [<li>cucumbers</li>, <li>carrots</li>, <li>corn</li>]
|
||||
cy.get("#nuts").nextUntil("#veggies")
|
||||
// yields [<li>cucumbers</li>, <li>carrots</li>, <li>corn</li>]
|
||||
cy.get('#nuts').nextUntil('#veggies')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Find all of the element's siblings before `#nuts` until `#veggies`
|
||||
**Find all of the element's siblings before `#nuts` until `#veggies`**
|
||||
|
||||
```javascript
|
||||
cy.get("#nuts").nextUntil("#veggies")
|
||||
cy.get('#nuts').nextUntil('#veggies')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -83,7 +109,7 @@ When clicking on `prevUntil` within the command log, the console outputs the fol
|
||||
|
||||
<img width="560" alt="screen shot 2017-03-23 at 2 45 36 pm" src="https://cloud.githubusercontent.com/assets/1271364/24264632/7743f57a-0fd7-11e7-99f8-c148acd17459.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [prev](https://on.cypress.io/api/prev)
|
||||
- [prevAll](https://on.cypress.io/api/prevall)
|
||||
|
||||
@@ -4,82 +4,36 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Reads a file and returns its contents. JSON is automatically parsed into JavaScript.
|
||||
Read a file and yield its contents.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the contents of the file |
|
||||
| **Timeout** | `cy.readFile` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
|
||||
# [cy.readFile( *filePath* )](#usage)
|
||||
|
||||
Reads the file at the `filePath`. The `filePath` is relative to the project's root.
|
||||
|
||||
# [cy.readFile( *filePath*, *encoding* )](#specify-encoding)
|
||||
|
||||
Reads the file at the `filePath` with the `encoding`. The `filePath` is relative to the project's root.
|
||||
|
||||
# Options
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.readFile`.
|
||||
|
||||
**[cy.readFile( *filePath*, *options* )](#options-usage)**
|
||||
|
||||
**[cy.readFile( *filePath*, *encoding*, *options* )](#options-usage)**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the `cy.readFile` command to be processed
|
||||
|
||||
# Usage
|
||||
|
||||
## Read a `txt` file
|
||||
|
||||
For any file other than JSON, the contents of the file are returned.
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
// message.txt contains:
|
||||
// Hello World
|
||||
|
||||
cy.readFile("path/to/message.txt").then(function (text) {
|
||||
expect(text).to.equal("Hello World") // true
|
||||
})
|
||||
cy.readFile(filePath)
|
||||
cy.readFile(filePath, encoding)
|
||||
cy.readFile(filePath, options)
|
||||
cy.readFile(filePath, encoding, options)
|
||||
```
|
||||
|
||||
## Read a `json` file
|
||||
## Usage
|
||||
|
||||
For JSON, the contents are parsed into JavaScript and returned.
|
||||
`cy.readFile()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
// data.json contains:
|
||||
// {
|
||||
// "name": "Eliza",
|
||||
// "email": "eliza@example.com"
|
||||
// }
|
||||
|
||||
cy.readFile("path/to/data.json").then(function (user) {
|
||||
// user will equal:
|
||||
// {
|
||||
// name: "Eliza",
|
||||
// email: "eliza@example.com"
|
||||
// }
|
||||
expect(user.name).to.equal("Eliza")
|
||||
})
|
||||
cy.readFile('menu.json')
|
||||
```
|
||||
|
||||
## Specify encoding
|
||||
## Arguments
|
||||
|
||||
Specify the encoding with the second argument.
|
||||
**{% fa fa-angle-right %} filePath** ***(String)***
|
||||
|
||||
```javascript
|
||||
cy.readFile("path/to/logo.png", "base64").then(function (logo) {
|
||||
// logo will be encoded as base64
|
||||
// and should look something like this:
|
||||
// aIJKnwxydrB10NVWqhlmmC+ZiWs7otHotSAAAOw==...
|
||||
})
|
||||
```
|
||||
A path to a file within the project root (the directory that contains `cypress.json`).
|
||||
|
||||
The following encodings are supported:
|
||||
**{% fa fa-angle-right %} encoding** ***(String)***
|
||||
|
||||
The encoding to be used when reading the file. The following encodings are supported:
|
||||
|
||||
* `ascii`
|
||||
* `base64`
|
||||
@@ -93,9 +47,93 @@ The following encodings are supported:
|
||||
* `utf16le`
|
||||
* `utf-16le`
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.readFile()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the command to be processed
|
||||
|
||||
## Yields
|
||||
|
||||
`cy.readFile()` yields the contents of the file.
|
||||
|
||||
## Timeout
|
||||
|
||||
`cy.readFile()` will wait up for the duration of [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the server to process the command.
|
||||
|
||||
# Examples
|
||||
|
||||
## Text
|
||||
|
||||
**Read a `txt` file**
|
||||
|
||||
For any file other than JSON, the contents of the file are returned.
|
||||
|
||||
***message.txt***
|
||||
```text
|
||||
Hello World
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy.readFile('path/to/message.txt').then(function (text) {
|
||||
expect(text).to.equal('Hello World') // true
|
||||
})
|
||||
```
|
||||
|
||||
## JSON
|
||||
|
||||
For JSON, the contents yielded are parsed into JavaScript and returned.
|
||||
|
||||
***Data.json***
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Eliza",
|
||||
"email": "eliza@example.com"
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy.readFile('path/to/data.json').then(function (user) {
|
||||
expect(user.name).to.equal('Eliza') // true
|
||||
})
|
||||
```
|
||||
|
||||
## YAML
|
||||
|
||||
**Get translation data from Yaml file**
|
||||
|
||||
```javascript
|
||||
YAML = require('yamljs')
|
||||
|
||||
cy.readFile("languages/en.yml").then(function (yamlString) {
|
||||
this.english = YAML.parse(yamlString)
|
||||
})
|
||||
|
||||
cy.get("#sidebar")
|
||||
.find(".sidebar-title").each(function (displayedTitle, i) {
|
||||
englishTitle = this.english.sidebar[@sidebarTitles[i]]
|
||||
expect(displayedTitle.text()).to.eq(englishTitle)
|
||||
})
|
||||
```
|
||||
|
||||
## Encoding
|
||||
|
||||
**Specify the encoding with the second argument.**
|
||||
|
||||
```javascript
|
||||
cy.readFile('path/to/logo.png', 'base64').then(function (logo) {
|
||||
// logo will be encoded as base64
|
||||
// and should look something like this:
|
||||
// aIJKnwxydrB10NVWqhlmmC+ZiWs7otHotSAAAOw==...
|
||||
})
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
## Implicit assertion
|
||||
**Implicit file existence assertion**
|
||||
|
||||
By default, `cy.readFile` asserts that the file exists and will fail if it does not exist. It will retry reading the file if it does not initially exist until the file exists or the command times out.
|
||||
|
||||
@@ -104,7 +142,7 @@ By default, `cy.readFile` asserts that the file exists and will fail if it does
|
||||
cy.readFile('does-not-exist.yaml')
|
||||
```
|
||||
|
||||
## Asserting non-existence
|
||||
**Asserting file non-existence**
|
||||
|
||||
You can assert that a file does not exist like so:
|
||||
|
||||
@@ -115,10 +153,10 @@ cy.readFile('does-not-exist.yaml').should("not.exist")
|
||||
|
||||
# Command Log
|
||||
|
||||
## List the contents of cypress.json
|
||||
**List the contents of cypress.json**
|
||||
|
||||
```javascript
|
||||
cy.readFile("cypress.json")
|
||||
cy.readFile('cypress.json')
|
||||
```
|
||||
|
||||
The command above will display in the command log as:
|
||||
@@ -129,7 +167,9 @@ When clicking on the `readFile` command within the command log, the console outp
|
||||
|
||||
<img width="689" alt="screen shot of console output" src="https://cloud.githubusercontent.com/assets/1157043/17934460/089e0652-69e6-11e6-9f00-7eb282be0d27.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [writeFile](https://on.cypress.io/api/writeFile)
|
||||
- [exec](https://on.cypress.io/api/exec)
|
||||
- [fixture](https://on.cypress.io/api/fixture)
|
||||
- [Creating Fixtures](https://on.cypress.io/guides/creating-fixtures)
|
||||
- [writeFile](https://on.cypress.io/api/writeFile)
|
||||
|
||||
@@ -6,53 +6,71 @@ description: ''
|
||||
|
||||
Reload the page.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the `window` object of the newly reloaded page |
|
||||
| **Timeout** | `cy.reload` will retry for the duration of the [pageLoadTimeout](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's [options](#options). |
|
||||
# Syntax
|
||||
|
||||
# [cy.reload()](#usage)
|
||||
```javascript
|
||||
cy.reload()
|
||||
cy.reload(forceReload)
|
||||
cy.reload(options)
|
||||
cy.reload(forceReload, options)
|
||||
```
|
||||
|
||||
Reload the page from the current URL.
|
||||
## Usage
|
||||
|
||||
# [cy.reload( *forceReload* )](#force-reload-usage)
|
||||
`.reload()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
Reload the current page, without using the cache if `forceReload` is true
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# Options
|
||||
```javascript
|
||||
cy.reload()
|
||||
```
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.reload`.
|
||||
## Arguments
|
||||
|
||||
**cy.reload( *options* )**
|
||||
**{% fa fa-angle-right %} forceReload** ***(Boolean)***
|
||||
|
||||
Whether to reload the current page without using the cache. `true` forces the reload without cache.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`timeout` | [pageLoadTimeout](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the visit
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [pageLoadTimeout](https://on.cypress.io/guides/configuration#timeouts) | Total time to reload the page
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Reload the page as if the user clicked the Refresh button
|
||||
`.reload()` yields the `window` object of the newly loaded page.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.reload()` will wait for the load event of the newly loaded page for the duration of the [pageLoadTimeout](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's options.
|
||||
|
||||
# Examples
|
||||
|
||||
## Reload
|
||||
|
||||
**Reload the page as if the user clicked 'Refresh'**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.visit("http://localhost:3000/admin")
|
||||
.reload()
|
||||
cy.visit('http://localhost:3000/admin')
|
||||
cy.get('#undo-btn').click().should('not.be.visible')
|
||||
cy.reload()
|
||||
cy.get('#undo-btn').click().should('not.be.visible')
|
||||
```
|
||||
|
||||
# Force Reload Usage
|
||||
## Force Reload
|
||||
|
||||
## Reload the page without using the cache
|
||||
**Reload the page without using the cache**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.visit("http://localhost:3000/admin")
|
||||
.reload(true)
|
||||
cy.visit('http://localhost:3000/admin')
|
||||
cy.reload(true)
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Reload the page
|
||||
**Reload the page**
|
||||
|
||||
```javascript
|
||||
cy.reload()
|
||||
@@ -62,10 +80,12 @@ The commands above will display in the command log as:
|
||||
|
||||

|
||||
|
||||
When clicking on `cy.reload` within the command log, the console outputs the following:
|
||||
When clicking on `reload` within the command log, the console outputs the following:
|
||||
|
||||

|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [go](https://on.cypress.io/api/go)
|
||||
- [location](https://on.cypress.io/api/location)
|
||||
- [visit](https://on.cypress.io/api/visit)
|
||||
|
||||
@@ -4,157 +4,173 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Use `cy.request` to make HTTP requests. Great for talking to an external endpoint before, during, or after your tests for seeding, querying records, or API testing.
|
||||
Make an HTTP request.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the `response` as an object literal. |
|
||||
| **Timeout** | `cy.request` will wait for the response for the duration of the [responseTimeout](https://on.cypress.io/guides/configuration#timeouts) or the [`timeout`](#options) passed in the options object of the command. |
|
||||
# Syntax
|
||||
|
||||
# [cy.request( *url* )](#url-usage)
|
||||
```javascript
|
||||
cy.request(url)
|
||||
cy.request(url, body)
|
||||
cy.request(method, url)
|
||||
cy.request(method, url, body)
|
||||
cy.request(options)
|
||||
```
|
||||
|
||||
Makes a `GET` request using the specified url.
|
||||
## Usage
|
||||
|
||||
# [cy.request( *url*, *body* )](#url-and-body-usage)
|
||||
`.request()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
Make a `GET` request to the provided url with the provided body.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# [cy.request( *method*, *url* )](#method-and-url-usage)
|
||||
```javascript
|
||||
cy.request('http://dev.local/seed')
|
||||
```
|
||||
|
||||
Make a request using the provided method to the specified url.
|
||||
## Arguments
|
||||
|
||||
# [cy.request( *method*, *url*, *body* )](#method-and-url-and-body-usage)
|
||||
**{% fa fa-angle-right %} url** ***(String, Glob, RegExp)***
|
||||
|
||||
Additionally pass in the request `body` as a `String` or `Object Literal`. Cypress will set the `Accepts` request header and serialize the response body by its `Content-Type`.
|
||||
The `url` to make the request to.
|
||||
|
||||
# Options
|
||||
If you provide a non fully qualified domain name (FQDN), Cypress will make its best guess as to which host you want the `.request()` to use in the url.
|
||||
|
||||
1. If you make a `.request()` after visiting a page, Cypress assumes the url used for the `.visit()` is the host.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.visit('http://localhost:8080/app')
|
||||
.request('users/1.json') // <-- url is http://localhost:8080/users/1.json
|
||||
```
|
||||
|
||||
2. If you make a `.request()` prior to visiting a page, Cypress uses the host configured as the `baseUrl` property inside of `cypress.json`.
|
||||
|
||||
***cypress.json***
|
||||
|
||||
```json
|
||||
{
|
||||
"baseUrl": "http://localhost:1234"
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy.request('seed/admin') //<-- url is http://localhost:1234/seed/admin
|
||||
```
|
||||
|
||||
3. If Cypress cannot determine the host it will throw an error.
|
||||
|
||||
|
||||
**{% fa fa-angle-right %} body** ***(String, Object)***
|
||||
|
||||
A request `body` to be sent in the request. Cypress sets the `Accepts` request header and serializes the response body by its `Content-Type`.
|
||||
|
||||
**{% fa fa-angle-right %} method** ***(String)***
|
||||
|
||||
Make a request using the specific method (`GET`, `POST`, `PUT`...). If no method is defined, Cypress will do a `GET` request by default.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.request`.
|
||||
|
||||
**[cy.request( *options* )](#options-usage)**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`auth` | `null` | Any auth to send. Accepts an object literal.
|
||||
`body` | `null` | The Request Body to send along with the request.
|
||||
`failOnStatusCode` | `true` | Whether to fail on response codes other than `2xx` and `3xx`.
|
||||
`followRedirect` | `true` | Whether to automatically follow redirects.
|
||||
`form` | `false` | Whether to convert the `body` values to urlencoded content and automatically set the `x-www-form-urlencoded` header.
|
||||
`gzip` | `true` | Whether to accept the `gzip` encoding.
|
||||
`headers` | `null` | Any additional headers to send. Accepts an object literal.
|
||||
`auth` | `null` | Any auth to send; Accepts object literal
|
||||
`body` | `null` | Body to send along with the request
|
||||
`failOnStatusCode` | `true` | Whether to fail on response codes other than `2xx` and `3xx`
|
||||
`followRedirect` | `true` | Whether to automatically follow redirects
|
||||
`form` | `false` | Whether to convert the `body` values to url encoded content and set the `x-www-form-urlencoded` header
|
||||
`gzip` | `true` | Whether to accept the `gzip` encoding
|
||||
`headers` | `null` | Additional headers to send; Accepts object literal
|
||||
`log` | `true` | Whether to log the request in the Command Log
|
||||
`method` | `GET` | The HTTP method to use when making the request.
|
||||
`qs` | `null` | The query parameters to be appended to the `url` option when making the request.
|
||||
`method` | `GET` | The HTTP method to use in the request
|
||||
`qs` | `null` | Query parameters to append to the `url` of the request
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for a response (in ms)
|
||||
`url` | `null` | The URL to make the request.
|
||||
`url` | `null` | The URL to make the request to
|
||||
|
||||
You can also set options for the `cy.request`'s `baseUrl` and `responseTimeout` globally in [configuration](https://on.cypress.io/guides/configuration).
|
||||
You can also set options for the `.request`'s `baseUrl` and `responseTimeout` globally in [configuration](https://on.cypress.io/guides/configuration).
|
||||
|
||||
# URL Usage
|
||||
## Yields
|
||||
|
||||
## Make a `GET` request
|
||||
`.request()` yields the `response` as an object literal containing properties such as `status`, `body`, `headers`, and `duration`.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.request()` will wait for the response for the duration of the [responseTimeout](https://on.cypress.io/guides/configuration#timeouts) or the `timeout` passed in the options object of the command.
|
||||
|
||||
# Examples
|
||||
|
||||
## URL
|
||||
|
||||
**Make a `GET` request**
|
||||
|
||||
`.request()` is great for talking to an external endpoint before your tests to seed a database.
|
||||
|
||||
```javascript
|
||||
// make a request to seed the database prior to running each test
|
||||
beforeEach(function(){
|
||||
cy.request("http://localhost:8080/db/seed")
|
||||
cy.request('http://localhost:8080/db/seed')
|
||||
})
|
||||
```
|
||||
|
||||
## Issue a simple HTTP request
|
||||
**Issue a simple HTTP request**
|
||||
|
||||
Sometimes it is quicker to simply test the contents of a page rather than `.visit()` and wait for the entire page and all of it's resource to load.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
// dont visit this page and load the resources
|
||||
// instead let's just issue a simple HTTP request
|
||||
// so we can make an assertion about its body
|
||||
.request("/admin")
|
||||
.its("body")
|
||||
.should("include", "<h2>admin.html</h2>")
|
||||
cy.request('/admin').its('body').should('include', '<h1>Admin</h1>')
|
||||
```
|
||||
|
||||
## Send the new subject to an HTTP's response on request
|
||||
## Method and URL
|
||||
|
||||
```javascript
|
||||
// the response object is an object literal
|
||||
// containing status, body, headers, and duration
|
||||
cy.request("http://dev.local/users").then(function(response){
|
||||
// subject is now the response object
|
||||
// {
|
||||
// status: 200,
|
||||
// headers: {...},
|
||||
// body: [{id: 1, name: "Jane"}, {id: 2, name: "LeeAnn"}],
|
||||
// duration: 28
|
||||
// }
|
||||
})
|
||||
```
|
||||
|
||||
# Method and URL Usage
|
||||
|
||||
## Send a `DELETE` request
|
||||
**Send a `DELETE` request**
|
||||
|
||||
```javascript
|
||||
// Delete a user
|
||||
cy.request("DELETE", "http://localhost:8888/users/827")
|
||||
cy.request('DELETE', 'http://localhost:8888/users/827')
|
||||
```
|
||||
|
||||
# Method and URL and Body Usage
|
||||
## Method, URL, and Body
|
||||
|
||||
## Send a `POST` request with a JSON body
|
||||
**Send a `POST` request with a JSON body**
|
||||
|
||||
```javascript
|
||||
// the Accepts Request Header is automatically set based
|
||||
// on the type of body you supply
|
||||
cy
|
||||
.request("POST", "http://localhost:8888/users/admin", {name: "Jane"})
|
||||
cy.request('POST', 'http://localhost:8888/users/admin', {name: 'Jane'})
|
||||
.then(function(response){
|
||||
// response.body would automatically be serialized into JSON
|
||||
expect(response.body).to.have.property("name", "Jane") // true
|
||||
// response.body is automatically serialized into JSON
|
||||
expect(response.body).to.have.property('name', 'Jane') // true
|
||||
})
|
||||
```
|
||||
|
||||
# Options Usage
|
||||
## Options
|
||||
|
||||
## Request the dashboard while disabling auto redirect
|
||||
**Request a page while disabling auto redirect**
|
||||
|
||||
To test the redirection behavior of a login without a session, `.request` can be used to check the `status` and `redirectedToUrl` property.
|
||||
|
||||
The `redirectedToUrl` property is a special Cypress property that normalizes the `url` the browser would normally follow during a redirect.
|
||||
|
||||
```javascript
|
||||
// to test the redirection behavior on login without a session
|
||||
// cy.request can be used to check the status code and redirectedToUrl property.
|
||||
//
|
||||
// the 'redirectedToUrl' property is a special Cypress property under the hood
|
||||
// that normalizes the url the browser would normally follow during a redirect
|
||||
|
||||
cy.request({
|
||||
url: '/dashboard',
|
||||
followRedirect: false // turn off following redirects automatically
|
||||
})
|
||||
.then((resp) => {
|
||||
// should have status code 302
|
||||
expect(resp.status).to.eq(302)
|
||||
|
||||
// when we turn off following redirects, Cypress will also send us
|
||||
// a 'redirectedToUrl' property with the fully qualified URL that we were redirected to.
|
||||
expect(resp.redirectedToUrl).to.eq("http://localhost:8082/unauthorized")
|
||||
})
|
||||
url: '/dashboard',
|
||||
followRedirect: false // turn off following redirects
|
||||
})
|
||||
.then((resp) => {
|
||||
// redirect status code is 302
|
||||
expect(resp.status).to.eq(302)
|
||||
expect(resp.redirectedToUrl).to.eq('http://localhost:8082/unauthorized')
|
||||
})
|
||||
```
|
||||
|
||||
## HTML form submissions using form option
|
||||
**HTML form submissions using form option**
|
||||
|
||||
Oftentimes, once we have a proper e2e test around logging in, there's no reason to continue going through the application's UI to log in users. `.visit()` waits for the entire page to load all associated resources before running any other commands. That would mean we'd have to wait before filling in and submitting the login form. Doing so slows down our entire test suite.
|
||||
|
||||
Using `.request()`, we can bypass all of this because it automatically gets and sets cookies just as if the requests had come from the browser.
|
||||
|
||||
```javascript
|
||||
// oftentimes once we have a proper e2e test around logging in
|
||||
// there is NO more reason to actually use our UI to log in users
|
||||
// doing so wastes a huge amount of time, as our entire page has to load
|
||||
// all associated resources, we have to wait to fill the
|
||||
// form and for the form submission and redirection process
|
||||
//
|
||||
// with cy.request we can bypass all of this because it automatically gets
|
||||
// and sets cookies under the hood which acts exactly as if these requests
|
||||
// came from the browser
|
||||
|
||||
cy
|
||||
.request({
|
||||
method: 'POST',
|
||||
url: '/login_with_form', // baseUrl will be prepended to this url
|
||||
url: '/login_with_form', // baseUrl is prepended to url
|
||||
form: true, // indicates the body should be form urlencoded and sets Content-Type: application/x-www-form-urlencoded headers
|
||||
body: {
|
||||
username: 'jane.lane',
|
||||
@@ -163,67 +179,40 @@ cy
|
||||
})
|
||||
|
||||
// just to prove we have a session
|
||||
cy.getCookie("cypress-session-cookie").should('exist')
|
||||
cy.getCookie('cypress-session-cookie').should('exist')
|
||||
```
|
||||
|
||||
{% note info Using cy.request for HTML Forms %}
|
||||
**Using cy.request for HTML Forms**
|
||||
|
||||
{% note info %}
|
||||
[Check out our example recipe using cy.request for HTML form submissions](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_html_web_form_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
# Notes
|
||||
|
||||
## Why don't I see the XHR in the Network Tab of the Chrome Dev Tools?
|
||||
**Request is not displayed in the Network Tab of Dev Tools?**
|
||||
|
||||
Cypress does not actually make an XHR request out of the browser. Under the hood we are making the HTTP request from the desktop application (in node). Therefore you will not see the request inside of the Chrome Dev Tools.
|
||||
Cypress does not *actually* make an XHR request from the browser. We are actually making the HTTP request from the Cypress desktop application (in Node.js). So, you won't see the request inside of the Dev Tools.
|
||||
|
||||
Note that we automatically set both Cookies + User Agent headers correctly as if the request was really coming from the browser.
|
||||
**CORS is bypassed**
|
||||
|
||||
## CORS is bypassed
|
||||
|
||||
Normally when the browser detects a cross-origin HTTP request, it will send an `OPTIONS` preflight check to ensure the server allows cross-origin requests. `cy.request` bypasses CORS entirely.
|
||||
Normally when the browser detects a cross-origin HTTP request, it will send an `OPTIONS` preflight check to ensure the server allows cross-origin requests, but `.request()` bypasses CORS entirely.
|
||||
|
||||
```javascript
|
||||
// we can make requests to any external server, no problem.
|
||||
cy
|
||||
.request("https://www.google.com/webhp?#q=cypress.io+cors")
|
||||
.its("body")
|
||||
.should("include", "Testing, the way it should be") // true
|
||||
.request('https://www.google.com/webhp?#q=cypress.io+cors')
|
||||
.its('body')
|
||||
.should('include', 'Testing, the way it should be') // true
|
||||
```
|
||||
|
||||
## Cookies are automatically sent and received
|
||||
**Cookies are automatically sent and received**
|
||||
|
||||
Before sending the HTTP request, we will automatically attach cookies that would have otherwise been attached had the request come from the browser. Additionally, if a response has a `Set-Cookie` header, these are automatically set back on the browser cookies.
|
||||
Before sending the HTTP request, we automatically attach cookies that would have otherwise been attached had the request come from the browser. Additionally, if a response has a `Set-Cookie` header, these are automatically set back on the browser cookies.
|
||||
|
||||
In other words, `cy.request` transparently performs all of the underlying functions as if it came from the browser.
|
||||
In other words, `.request()` transparently performs all of the underlying functions as if it came from the browser.
|
||||
|
||||
## Rules for resolving a relative request url
|
||||
|
||||
If you provide a non fully qualified domain name (FQDN), Cypress will make its best guess as to which host you want the request to go to.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
// after you visit somewhere, Cypress will assume this is the host
|
||||
.visit("http://localhost:8080/app")
|
||||
.request("users/1.json") // <-- url is http://localhost:8080/users/1.json
|
||||
```
|
||||
|
||||
If you make the `cy.request` prior to visiting a page, Cypress will use the host configured as the `baseUrl` property inside of `cypress.json`.
|
||||
|
||||
```javascript
|
||||
// cypress.json
|
||||
{
|
||||
baseUrl: "http://localhost:1234"
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// inside of your tests
|
||||
cy.request("seed/admin") //<-- url is http://localhost:1234/seed/admin
|
||||
```
|
||||
|
||||
If Cypress cannot determine the host it will throw an explicit error.
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [Recipe: Logging In - HTML Web Form](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_html_web_form_spec.js)
|
||||
- [Recipe: Logging In - XHR Web Form](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_xhr_web_form_spec.js)
|
||||
|
||||
@@ -4,7 +4,7 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the root element. By default the root is `document`. When calling `cy.root` in a [`cy.within`](https://on.cypress.io/api/within), the root element will be the return of the within command.
|
||||
Get the root element.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
@@ -45,10 +45,10 @@ cy.root()
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy.get("form").within(function(){
|
||||
cy.get('form').within(function(){
|
||||
cy
|
||||
.get("input[name='email']").type("john.doe@email.com")
|
||||
.get("input[name='password']").type("password")
|
||||
.get('input[name="email"]').type('john.doe@email.com')
|
||||
.get('input[name="password"]').type('password')
|
||||
|
||||
// the root element in a within is the previous
|
||||
// commands subject, in this case <form>
|
||||
@@ -56,7 +56,7 @@ cy.get("form").within(function(){
|
||||
})
|
||||
```
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [get](https://on.cypress.io/api/get)
|
||||
- [within](https://on.cypress.io/api/within)
|
||||
|
||||
@@ -4,45 +4,57 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Use `cy.route` to manage the behavior of network requests.
|
||||
|
||||
{% note info New to Cypress? %}
|
||||
[Read about Network Requests first.](https://on.cypress.io/guides/network-requests-xhr)
|
||||
{% endnote %}
|
||||
|
||||
Use `cy.route` to manage the behavior of network requests.
|
||||
# Syntax
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | `null` |
|
||||
| **Timeout** | *cannot timeout* |
|
||||
```javascript
|
||||
cy.route(url)
|
||||
cy.route(url, response)
|
||||
cy.route(method, url)
|
||||
cy.route(method, url, response)
|
||||
cy.route(function() {})
|
||||
cy.route(options)
|
||||
```
|
||||
|
||||
# [cy.route( *url* )](#url-usage)
|
||||
## Usage
|
||||
|
||||
Set a route matching the specific `url` which is not stubbed but can be waited on later. This will match `GET` request methods.
|
||||
`cy.route()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
# [cy.route( *url*, *response* )](#url-and-response-usage)
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
Set a route matching the `url` stubbed with the supplied `response`. This will match `GET` request methods.
|
||||
```javascript
|
||||
cy.route('/users/**')
|
||||
```
|
||||
|
||||
# [cy.route( *method*, *url* )](#method-and-url-usage)
|
||||
## Arguments
|
||||
|
||||
Set a route matching the specific `method` and `url` which is not stubbed but can be waited on later.
|
||||
**{% fa fa-angle-right %} url** ***(String, Glob, RegExp)***
|
||||
|
||||
# [cy.route( *method*, *url*, *response* )](#method-url-and-response-usage)
|
||||
Set a route matching the specific `url` which is not stubbed but can be waited on later.
|
||||
|
||||
Set a route matching the `method` and `url` stubbed with the supplied `response`.
|
||||
**{% fa fa-angle-right %} response** ***(String, Object)***
|
||||
|
||||
# [cy.route( *function* )](#function-usage)
|
||||
Supply a response body to *stub* in the matching route.
|
||||
|
||||
Set a route by returning an object literal from your callback function.
|
||||
**{% fa fa-angle-right %} method** ***(String)***
|
||||
|
||||
Match the route to a specific method (`GET`, `POST`, `PUT`...). If no method is defined, Cypress will match `GET` requests by default.
|
||||
|
||||
**{% fa fa-angle-right %} function** ***(Function)***
|
||||
|
||||
Set a route by returning an object literal from a callback function.
|
||||
|
||||
Functions which return a promise will automatically be awaited.
|
||||
|
||||
# Options
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.route`. By default `cy.route` inherits its options from [`cy.server`](https://on.cypress.io/api/server).
|
||||
|
||||
**[cy.route( *options* )](#options-usage)**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`method` | `GET` | method to match against requests
|
||||
@@ -51,96 +63,84 @@ Option | Default | Notes
|
||||
`status` | `200` | response status code when stubbing routes
|
||||
`delay` | `0` | delay for stubbed responses (in ms)
|
||||
`headers` | `null` | response headers for stubbed routes
|
||||
`force404` | `false` | forcibly send XHR's to 404 status when these XHR's do not match any existing [`cy.routes`](https://on.cypress.io/api/routes)
|
||||
`force404` | `false` | forcibly send XHR's a 404 status when the XHR's do not match any existing [`cy.routes`](https://on.cypress.io/api/routes)
|
||||
`onRequest` | `null` | callback function when a request is sent
|
||||
`onResponse` | `null` | callback function when a response is returned
|
||||
`onAbort` | `null` | callback function which fires anytime an XHR is aborted
|
||||
|
||||
You can also set options for all [cy.wait](https://on.cypress.io/api/wait) `requestTimeout` and `responseTimeout` globally in [configuration](https://on.cypress.io/guides/configuration) to control how long to wait for the request and response of the supplied route.
|
||||
You can also set options for all [cy.wait](https://on.cypress.io/api/wait) `requestTimeout` and `responseTimeout` globally in [configuration](https://on.cypress.io/guides/configuration) to control how long to wait for the request and response of a supplied route.
|
||||
|
||||
# Url Usage
|
||||
## Yields
|
||||
|
||||
## Wait on non-stubbed XHR's by url
|
||||
## Timeout
|
||||
|
||||
# Examples
|
||||
|
||||
## Non-stubbed requests
|
||||
|
||||
If you do not pass a `response` to a route, Cypress will pass this request through without stubbing it. We can still wait for the request to resolve later.
|
||||
|
||||
**Wait on XHR request matching `url`**
|
||||
|
||||
```javascript
|
||||
// by not passing a response to the route
|
||||
// Cypress will pass this request through
|
||||
// without stubbing it - but still allow
|
||||
// us to wait for it later
|
||||
cy
|
||||
.server()
|
||||
.route(/users/).as("getUsers")
|
||||
.visit("/users")
|
||||
.wait("@getUsers")
|
||||
.route('/users/**').as('getUsers')
|
||||
.visit('/users')
|
||||
.wait('@getUsers')
|
||||
```
|
||||
|
||||
# Method and Url Usage
|
||||
|
||||
## Wait on non-stubbed XHR's by method + url
|
||||
**Wait on XHR's matching `method` and `url`**
|
||||
|
||||
```javascript
|
||||
// by not passing a response to the route
|
||||
// Cypress will pass this request through
|
||||
// without stubbing it - but still allow
|
||||
// us to wait for it later
|
||||
cy
|
||||
.server()
|
||||
.route("POST", /users/).as("postUser")
|
||||
.visit("/users")
|
||||
.get("#first-name").type("Julius{enter}")
|
||||
.wait("@postUser")
|
||||
.route('POST', /users/).as('postUser')
|
||||
.visit('/users')
|
||||
.get('#first-name').type('Julius{enter}')
|
||||
.wait('@postUser')
|
||||
```
|
||||
|
||||
{% note info Setup route to POST to login %}
|
||||
[Check out our example recipe using cy.route to POST for login](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_xhr_web_form_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
# Url and Response Usage
|
||||
**Wait on `url` matching glob**
|
||||
|
||||
## Url as a string
|
||||
Under the hood Cypress uses [minimatch](https://github.com/isaacs/minimatch) to match glob patterns of `url`.
|
||||
|
||||
When passing a `string` as the `url`, the XHR's URL must match exactly what you've written.
|
||||
This means you can take advantage of `*` and `**` support. This makes it *much* easier to route against dynamic segments without having to build up a complex `RegExp`.
|
||||
|
||||
We expose [`Cypress.minimatch`](https://on.cypress.io/api/cypress-minimatch) as a function that you can use in your console to test routes.
|
||||
|
||||
***Match route against any UserId***
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route("/users", [{id: 1, name: "Pat"}])
|
||||
```
|
||||
|
||||
## Url as a string glob
|
||||
|
||||
As of `0.16.3` we now accept glob patterns. Under the hood Cypress is using [minimatch](https://github.com/isaacs/minimatch) to match glob patterns with URL's.
|
||||
|
||||
This means you can take advantage of `*` and `**` support. This makes it **much** easier to route against dynamic segments without having to build up a complex `regex`.
|
||||
|
||||
We expose [`Cypress.minimatch`](https://on.cypress.io/api/cypress-minimatch) as a function which you can use in your Dev Tools console to test routes. You can iterate much faster on a working pattern than guessing at why something isn't working.
|
||||
|
||||
```javascript
|
||||
// match against any user id
|
||||
// /users/123/comments <-- matches
|
||||
// /users/123/comments/465 <-- not matches
|
||||
cy
|
||||
.server()
|
||||
.route("/users/*/comments")
|
||||
.route('/users/*/comments')
|
||||
```
|
||||
|
||||
***Use glob to match all segments***
|
||||
|
||||
```javascript
|
||||
// use ** glob to match all segments
|
||||
// /posts/1 <-- matches
|
||||
// /posts/foo/bar/baz <-- matches
|
||||
// /posts/quuz?a=b&1=2 <-- matches
|
||||
cy
|
||||
.server()
|
||||
.route("/posts/**")
|
||||
.route('/posts/**')
|
||||
```
|
||||
|
||||
## Override Url options
|
||||
**Override `url` glob matching options**
|
||||
|
||||
When we check `glob` patterns with `minimatch` by default we use `{ matchBase: true}`.
|
||||
When we check `glob` patterns with [minimatch](https://github.com/isaacs/minimatch), by default we use `{ matchBase: true }`.
|
||||
|
||||
You can override these options in `cy.server`.
|
||||
You can override these options in [`cy.server`](https://on.cypress.io/api/server) options.
|
||||
|
||||
If you'd like to permanently override these options you can do so by setting [`Cypress.Server.defaults(...)`](https://on.cypress.io/api/api-server).
|
||||
If you'd like to permanently override these options you could do so by setting [`Cypress.Server.defaults(...)`](https://on.cypress.io/api/api-server).
|
||||
|
||||
```javascript
|
||||
cy
|
||||
@@ -150,278 +150,39 @@ cy
|
||||
.route(...)
|
||||
```
|
||||
|
||||
## Url as a RegExp
|
||||
## Stubbed requests
|
||||
|
||||
If you do pass a `response` to a route, Cypress will stub the response in the request.
|
||||
|
||||
**`url` as a string**
|
||||
|
||||
When passing a `string` as the `url`, the XHR's URL must match *exactly* what you've written.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route('/users', [{id: 1, name: 'Pat'}])
|
||||
```
|
||||
|
||||
**`url` as a RegExp**
|
||||
|
||||
When passing a RegExp as the `url`, the XHR's url will be tested against the regular expression and will apply if it passes.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route(/users\/\d+/, {id: 1, name: "Phoebe"})
|
||||
.route(/users\/\d+/, {id: 1, name: 'Phoebe'})
|
||||
```
|
||||
|
||||
```javascript
|
||||
// Application Code
|
||||
|
||||
$.get("/users/1337", function(data){
|
||||
$.get('/users/1337', function(data){
|
||||
console.log(data) // => {id: 1, name: "Phoebe"}
|
||||
})
|
||||
```
|
||||
|
||||
## Matching requests and routes
|
||||
|
||||
Any request that matches the `method` and `url` of a route will be responded to based on the configuration of that route.
|
||||
|
||||
If a request doesn't match any route [it will automatically receive a 404](#notes). For instance given we have the following routes:
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route(/users/, [{id: 19, name: "Laura"}, {id: 20, name: "Jamie"}])
|
||||
.route("POST", /messages/, {id: 123, message: "Hi There!"})
|
||||
.get("form").submit()
|
||||
```
|
||||
|
||||
```javascript
|
||||
// Application Code
|
||||
|
||||
// when our form is submitted
|
||||
$("form").submit(function(){
|
||||
// send an AJAX to: GET /users
|
||||
$.get("/users" )
|
||||
|
||||
// send an AJAX to: POST /messages
|
||||
$.post("/messages", {some: "data"})
|
||||
|
||||
// send an AJAX to: GET /updates
|
||||
$.get("/updates")
|
||||
})
|
||||
```
|
||||
|
||||
**The above application code will issue 3 AJAX requests:**
|
||||
|
||||
1. The `GET /users` will match our 1st route and respond with a 200 status code and the array of users.
|
||||
2. The `POST /messages` will match our 2nd route and respond with a 200 status code with the message object.
|
||||
3. The `GET /updates` did not match any routes and its response automatically sent back a 404 status code with an empty response body.
|
||||
|
||||
## Matching origins and non origin URL's
|
||||
|
||||
When Cypress matches up an outgoing XHR request to a `cy.route` it actually attempts to match it against both the fully qualified URL and then additionally without the URL's origin.
|
||||
|
||||
```javascript
|
||||
cy.route("/users/*")
|
||||
```
|
||||
|
||||
The following XHR's which were `xhr.open(...)` with these URLs would:
|
||||
|
||||
**Match**
|
||||
- /users/1
|
||||
- http://localhost:2020/users/2
|
||||
- https://google.com/users/3
|
||||
|
||||
**Not Match**
|
||||
- /users/4/foo
|
||||
- http://localhost:2020/users/5/foo
|
||||
|
||||
# Method, Url, and Response Usage
|
||||
|
||||
## Specify the method
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
|
||||
// match all DELETE requests to "/users"
|
||||
// and respond with an empty JSON object
|
||||
.route("DELETE", "/users", {})
|
||||
```
|
||||
|
||||
# Options Usage
|
||||
|
||||
## Pass in an options object
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route({
|
||||
method: "DELETE",
|
||||
url: /user\/\d+/,
|
||||
status: 412,
|
||||
response: {
|
||||
rolesCount: 2
|
||||
},
|
||||
delay: 500,
|
||||
headers: {
|
||||
"X-Token": null
|
||||
},
|
||||
onRequest: function(xhr) {
|
||||
// do something with the
|
||||
// raw XHR object when the
|
||||
// request initially goes out
|
||||
},
|
||||
onResponse: function(xhr) {
|
||||
// do something with the
|
||||
// raw XHR object when the
|
||||
// response comes back
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Simulate a server redirect
|
||||
|
||||
```javascript
|
||||
cy
|
||||
// simulate the server returning 503 with
|
||||
// empty JSON response body
|
||||
.route({
|
||||
method: 'POST',
|
||||
url: '/login',
|
||||
response: {
|
||||
// simulate a redirect to another page
|
||||
redirect: '/error'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
{% note info Setup route to error on POST to login %}
|
||||
[Check out our example recipe using cy.route to simulate a 503 on POST to login](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_xhr_web_form_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
## Use headers and fixtures for image route
|
||||
|
||||
```javascript
|
||||
cy.route({
|
||||
url: "image.png",
|
||||
response: "fx:logo.png,binary" // binary encoding
|
||||
headers: {
|
||||
"content-type": "binary/octet-stream" // set content-type headers
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Setting a delay for a specific route
|
||||
|
||||
You can optionally pass in a delay option which will cause a delay (in ms) to the response for matched requests. The example below will cause the response to be delayed by 3 secs.
|
||||
|
||||
```javascript
|
||||
cy.route({
|
||||
method: "PATCH",
|
||||
url: /activities\/\d+/,
|
||||
response: {},
|
||||
delay: 3000
|
||||
})
|
||||
```
|
||||
|
||||
# Function Usage
|
||||
|
||||
## Set the routing options by a callback function
|
||||
|
||||
```javascript
|
||||
cy.route(function(){
|
||||
// ...do some custom logic here..
|
||||
|
||||
// and return an appropriate routing object here
|
||||
return {
|
||||
method: "POST",
|
||||
url: "/users/*/comments",
|
||||
response: this.commentsFixture
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Functions which return promises are awaited
|
||||
|
||||
```javascript
|
||||
cy.route(function(){
|
||||
// a silly example of async return
|
||||
return new Cypress.Promise(function(resolve){
|
||||
// resolve this promise after 1 second
|
||||
setTimeout(function(){
|
||||
resolve({
|
||||
method: "PUT"
|
||||
url: "/posts/**"
|
||||
response: "@postFixture"
|
||||
})
|
||||
}, 1000)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
## Understanding Stubbed vs Regular XHR's
|
||||
|
||||
Cypress indicates whether an XHR sent back a stubbed response vs actually going out to a server.
|
||||
|
||||
XHR's that indicate `(XHR STUB)` in the Command Log have been stubbed and their response, status, headers, and delay have been controlled by your matching `cy.route`.
|
||||
|
||||
XHR's that indicate `(XHR)` in the Command Log have not been stubbed and were passed directly through to a server.
|
||||
|
||||

|
||||
|
||||
Cypress also logs whether the XHR was stubbed or not to the console when you click on the command in the Command Log. It will indicate whether a request was stubbed, which url it matched or that it did not match any routes.
|
||||
|
||||

|
||||
|
||||
Even the `Initiator` is included, which is a stack trace to what caused the XHR to be sent.
|
||||
|
||||
## Requests that don't match a route
|
||||
|
||||
You can force routes that do not match a route to return 404:
|
||||
|
||||
Status | Body | Headers
|
||||
--- | --- | ---
|
||||
`404` | "" | `null`
|
||||
|
||||
If you'd like to enable this behavior you need to pass:
|
||||
|
||||
```javascript
|
||||
cy.server({force404: true})
|
||||
```
|
||||
|
||||
You can [read more about this here.](https://on.cypress.io/api/server#prevent-sending-404s-to-unmatched-requests)
|
||||
|
||||
## Using Fixtures as Responses
|
||||
|
||||
Instead of writing a response inline you can automatically connect a response with a fixture.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route(/posts/, "fixture:logo.png").as("getLogo")
|
||||
.route(/users/, "fixture:users/all.json").as("getUsers")
|
||||
.route(/admin/, "fixtures:users/admin.json").as("getAdmin")
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy
|
||||
// route after receiving the fixture and
|
||||
// working with the data
|
||||
.fixture("user").then(function(user){
|
||||
user.firstName = "Jennifer"
|
||||
|
||||
// work with the users array here
|
||||
cy.route("GET", "user/123", user)
|
||||
})
|
||||
.visit("/users")
|
||||
.get(".user").should("include", "Jennifer")
|
||||
```
|
||||
|
||||
You can also reference fixtures as strings directly in the response
|
||||
|
||||
```javascript
|
||||
// we can link responses to fixtures simply
|
||||
// by passing the fixture string with an '@'
|
||||
// just like how you use aliases in
|
||||
// cy.get(...) and cy.wait(...)
|
||||
cy
|
||||
.fixture("user").as("fxUser")
|
||||
.route("POST", "/users/*", "@fxUser")
|
||||
```
|
||||
|
||||
You can [read more about fixtures here.](https://on.cypress.io/api/fixture)
|
||||
|
||||
## Using Response Functions
|
||||
**Response Functions**
|
||||
|
||||
You can also use a function as a response which enables you to add logic surrounding the response.
|
||||
|
||||
@@ -436,23 +197,269 @@ var commentsResponse = function(routeData){
|
||||
}
|
||||
}
|
||||
|
||||
cy.route("POST", "/comments/**", commentsResponse)
|
||||
cy.route('POST', '/comments/**', commentsResponse)
|
||||
```
|
||||
|
||||
## Response Headers are automatically set
|
||||
**Matching requests and routes**
|
||||
|
||||
Any request that matches the `method` and `url` of a route will be responded to based on the configuration of that route.
|
||||
|
||||
If a request doesn't match any route, [it will automatically receive a 404](#notes). For example, given we have the following routes:
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route(/users/, [
|
||||
{id: 19, name: 'Laura'},
|
||||
{id: 20, name: 'Jamie'}
|
||||
])
|
||||
.route('POST', /messages/, {id: 123, message: 'Hi There!'})
|
||||
.get('form').submit()
|
||||
```
|
||||
|
||||
```javascript
|
||||
// Application Code
|
||||
|
||||
// when our form is submitted
|
||||
$('form').submit(function(){
|
||||
// send an AJAX to: GET /users
|
||||
$.get('/users' )
|
||||
|
||||
// send an AJAX to: POST /messages
|
||||
$.post('/messages', {some: 'data'})
|
||||
|
||||
// send an AJAX to: GET /updates
|
||||
$.get('/updates')
|
||||
})
|
||||
```
|
||||
|
||||
***The above application code will issue 3 AJAX requests:***
|
||||
|
||||
1. The `GET /users` will match our 1st route and respond with a `200` status code and the array of users.
|
||||
2. The `POST /messages` will match our 2nd route and respond with a `200` status code with the message object.
|
||||
3. The `GET /updates` did not match any routes and its response automatically sent back a `404` status code with an empty response body.
|
||||
|
||||
**Specify the method**
|
||||
|
||||
The below example matches all `DELETE` requests to "/users" and stubs a response with an empty JSON object.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route('DELETE', '/users', {})
|
||||
```
|
||||
|
||||
## Using Fixtures as Responses
|
||||
|
||||
Instead of writing a response inline you can automatically connect a response with a [fixture](https://on.cypress.io/api/fixture).
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route('/posts/*', 'fixture:logo.png').as('getLogo')
|
||||
.route('/users/*', 'fixture:users/all.json').as('getUsers')
|
||||
.route('/admin/*', 'fixtures:users/admin.json').as('getAdmin')
|
||||
```
|
||||
|
||||
You may want to define the `cy.route()` after receiving the fixture and working with it's data.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.fixture('user').then(function(user){
|
||||
user.firstName = 'Jane'
|
||||
// work with the users array here
|
||||
|
||||
cy.route('GET', 'user/123', user)
|
||||
})
|
||||
.visit('/users')
|
||||
.get('.user').should('include', 'Jane')
|
||||
```
|
||||
|
||||
You can also reference fixtures as strings directly in the response by passing the fixture string with an `@` just like how aliases work.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.fixture('user').as('fxUser')
|
||||
.route('POST', '/users/*', '@fxUser')
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
**Pass in an options object**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route({
|
||||
method: 'DELETE',
|
||||
url: '/user/*',
|
||||
status: 412,
|
||||
response: {
|
||||
rolesCount: 2
|
||||
},
|
||||
delay: 500,
|
||||
headers: {
|
||||
'X-Token': null
|
||||
},
|
||||
onRequest: function(xhr) {
|
||||
// do something with the
|
||||
// raw XHR object when the
|
||||
// request initially goes out
|
||||
},
|
||||
onResponse: function(xhr) {
|
||||
// do something with the
|
||||
// raw XHR object when the
|
||||
// response comes back
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Simulate a server redirect**
|
||||
|
||||
Below we simulate the server returning `503` with a stubbed empty JSON response body.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.route({
|
||||
method: 'POST',
|
||||
url: '/login',
|
||||
response: {
|
||||
// simulate a redirect to another page
|
||||
redirect: '/error'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
{% note info Setup route to error on POST to login %}
|
||||
[Check out our example recipe using cy.route to simulate a 503 on POST to login](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_xhr_web_form_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
**Change `headers`**
|
||||
|
||||
By default, Cypress will automatically set `Content-Type` and `Content-Length` based on what your `response body` looks like.
|
||||
|
||||
If you'd like to override this, explicitly pass in `headers` as an `object literal`.
|
||||
|
||||
```javascript
|
||||
cy.route({
|
||||
url: 'image.png',
|
||||
response: 'fx:logo.png,binary' // binary encoding
|
||||
headers: {
|
||||
// set content-type headers
|
||||
'content-type': 'binary/octet-stream'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Using delays for route responses**
|
||||
|
||||
You can pass in a `delay` option that causes a delay (in ms) to the `response` for matched requests. The example below will cause the response to be delayed by 3 secs.
|
||||
|
||||
```javascript
|
||||
cy.route({
|
||||
method: 'PATCH',
|
||||
url: '/activities/*',
|
||||
response: {},
|
||||
delay: 3000
|
||||
})
|
||||
```
|
||||
|
||||
## Function
|
||||
|
||||
**Set the routing options by a callback function**
|
||||
|
||||
```javascript
|
||||
cy.route(function(){
|
||||
// ...do some custom logic here..
|
||||
|
||||
// and return an appropriate routing object here
|
||||
return {
|
||||
method: 'POST',
|
||||
url: '/users/*/comments',
|
||||
response: this.commentsFixture
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Functions that return promises are awaited**
|
||||
|
||||
```javascript
|
||||
cy.route(function(){
|
||||
// a silly example of async return
|
||||
return new Cypress.Promise(function(resolve){
|
||||
// resolve this promise after 1 second
|
||||
setTimeout(function(){
|
||||
resolve({
|
||||
method: 'PUT'
|
||||
url: '/posts/**'
|
||||
response: '@postFixture'
|
||||
})
|
||||
}, 1000)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
**Understanding Stubbed vs Regular XHR's**
|
||||
|
||||
Cypress indicates whether an XHR sent back a stubbed response or actually went out to a server in it's Command Log
|
||||
|
||||
XHR's that display `(XHR STUB)` in the Command Log have been stubbed and their response, status, headers, and delay have been controlled by your matching `cy.route`.
|
||||
|
||||
XHR's that display `(XHR)` in the Command Log have *not* been stubbed and were passed directly through to a server.
|
||||
|
||||

|
||||
|
||||
Cypress also logs whether the XHR was stubbed or not to the console when you click on the command in the Command Log. It will indicate whether a request was stubbed, which url it matched or that it did not match any routes.
|
||||
|
||||

|
||||
|
||||
Even the `Initiator` is included, which is a stack trace to what caused the XHR to be sent.
|
||||
|
||||
**Matching origins and non origin URL's**
|
||||
|
||||
When Cypress matches up an outgoing XHR request to a `cy.route`, it actually attempts to match it against both the fully qualified URL and then additionally without the URL's origin.
|
||||
|
||||
```javascript
|
||||
cy.route('/users/*')
|
||||
```
|
||||
|
||||
The following XHR's which were `xhr.open(...)` with these URLs would:
|
||||
|
||||
***Match***
|
||||
- /users/1
|
||||
- http://localhost:2020/users/2
|
||||
- https://google.com/users/3
|
||||
|
||||
***Not Match***
|
||||
- /users/4/foo
|
||||
- http://localhost:2020/users/5/foo
|
||||
|
||||
**Requests that don't match any routes**
|
||||
|
||||
You can force routes that do not match a route to return `404`:
|
||||
|
||||
Status | Body | Headers
|
||||
--- | --- | ---
|
||||
`404` | "" | `null`
|
||||
|
||||
If you'd like to enable this behavior you need to pass:
|
||||
|
||||
```javascript
|
||||
cy.server({force404: true})
|
||||
```
|
||||
|
||||
You can [read more about this here.](https://on.cypress.io/api/server#prevent-sending-404s-to-unmatched-requests)
|
||||
|
||||
# Command Log
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route(/accounts/).as("accountsGet")
|
||||
.route(/company/, "fixtures:company").as("companyGet")
|
||||
.route(/teams/, "fixtures:teams").as("teamsGet")
|
||||
.route(/accounts/).as('accountsGet')
|
||||
.route(/company/, 'fixtures:company').as('companyGet')
|
||||
.route(/teams/, 'fixtures:teams').as('teamsGet')
|
||||
```
|
||||
|
||||
Whenever you start a server and add routes, Cypress will display a new Instrument Log called **Routes**. It will list the routing table in the Instrument Log, including the `method`, `url`, `stubbed`, `alias` and number of matched requests:
|
||||
@@ -467,7 +474,7 @@ When clicking on `XHR Stub` within the Command Log, the console outputs the foll
|
||||
|
||||

|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [Guide: Network Requests](https://on.cypress.io/guides/network-requests-xhr)
|
||||
- [Recipe: Loggin in - XHR Web Form](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_xhr_web_form_spec.js)
|
||||
|
||||
@@ -4,90 +4,104 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Take a screenshot of the Command Log and the test runner (the app being tested). The screenshot will be stored in `cypress/screenshots` by default.
|
||||
Take a screenshot of the application under test with the Cypress Command Log.
|
||||
|
||||
You can change the directory where screenshots are saved in your [configuration](https://on.cypress.io/guides/configuration#folders).
|
||||
# Syntax
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | `null` |
|
||||
| **Timeout** | `cy.screenshot` will wait up for the duration of [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the automation server to process this command. |
|
||||
```javascript
|
||||
cy.screenshot()
|
||||
cy.screenshot(fileName)
|
||||
cy.screenshot(options)
|
||||
cy.screenshot(fileName, options)
|
||||
```
|
||||
|
||||
# [cy.screenshot()](#usage)
|
||||
## Usage
|
||||
|
||||
Take a screenshot of the screen and save as a `.png` in `cypress/screenshots`. By default the filename will be the title of the test.
|
||||
`.screenshot()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
# [cy.screenshot( *filename* )](#filename-usage)
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
Take a screenshot of the screen and save as a `.png` in `cypress/screenshots`. The filename will be the filename passed in as the argument.
|
||||
```javascript
|
||||
cy.screenshot()
|
||||
```
|
||||
|
||||
# Options
|
||||
## Arguments
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.screenshot`.
|
||||
**{% fa fa-angle-right %} fileName** ***(String)***
|
||||
|
||||
**cy.screenshot( *options* )**
|
||||
**cy.screenshot( *filename*, *options* )**
|
||||
A name for the image file. By default the filename will be the title of the test.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.screenshot()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the automation server to process this command.
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the automation server to process the command.
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Take a screenshot
|
||||
`cy.screenshot()` yields `null`.
|
||||
|
||||
## Timeout
|
||||
|
||||
`cy.screenshot` will wait up for the duration of [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the automation server to process this command.
|
||||
|
||||
# Examples
|
||||
|
||||
The screenshot will be stored in the `cypress/screenshots` folder by default.
|
||||
|
||||
You can change the directory where screenshots are saved in your [configuration](https://on.cypress.io/guides/configuration#folders).
|
||||
|
||||
## Screenshot
|
||||
|
||||
**Take a screenshot**
|
||||
|
||||
```javascript
|
||||
// screenshot will be saved at
|
||||
// cypress/sreenshots/takes a screenshot.png
|
||||
it("takes a screenshot", function(){
|
||||
// returns null
|
||||
cy.screenshot()
|
||||
describe('my tests', function(){
|
||||
it('takes a screenshot', function(){
|
||||
cy.screenshot() // saved as 'cypress/sreenshots/my tests -- takes a screenshot.png'
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
# Filename Usage
|
||||
## Filename
|
||||
|
||||
## Take a screenshot and save as specific filename
|
||||
**Take a screenshot and save as specific filename**
|
||||
|
||||
```javascript
|
||||
// screenshot will be saved at
|
||||
// screenshot will be saved as
|
||||
// cypress/sreenshots/clickingOnNav.png
|
||||
cy.screenshot("clickingOnNav")
|
||||
cy.screenshot('clickingOnNav')
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
## Automatic screenshots on test failure
|
||||
**Automatic screenshots on test failure**
|
||||
|
||||
When running headlessly or in [Continuous Integration](https://on.cypress.io/guides/continuous-integration), Cypress will automatically take a screenshot when a test fails. You can optionally turn this off by setting `screenshotOnHeadlessFailure` to `false` in your [configuration](https://on.cypress.io/guides/configuration).
|
||||
When running headlessly or in [Continuous Integration](https://on.cypress.io/guides/continuous-integration), Cypress automatically takes a screenshot when a test fails. You can optionally turn this off by setting `screenshotOnHeadlessFailure` to `false` in your [configuration](https://on.cypress.io/guides/configuration).
|
||||
|
||||
## Default screenshots folder
|
||||
**Screenshots in CI**
|
||||
|
||||
By default, screenshots will be saved in `cypress/screenshots`. You can change the directory where screenshots are saved in your [configuration](https://on.cypress.io/guides/configuration#folders).
|
||||
You can see screenshots taken during a CI run in the [Cypress Dashboard](https://on.cypress.io/dashboard) without any extra work.
|
||||
|
||||
## Screenshots in CI
|
||||
Alternatively, to see screenshots in the [Circle CI](https://circleci.com/) UI, we automatically export screenshots as artifacts. This makes them available directly in their web UI.
|
||||
|
||||
When running in [Circle CI](https://circleci.com/), we will automatically export screenshots as artifacts. This makes them available directly in their web UI. If you're using Circle CI, you'll be able to see screenshots without doing anything.
|
||||
If you're using Travis, you'll need to upload artifacts to an s3 bucket as per their [uploading artifacts doc](https://docs.travis-ci.com/user/uploading-artifacts/) to see screenshots outside of the Cypress Dashboard.
|
||||
|
||||
If you're using Travis, you'll need to upload artifacts to an s3 bucket as per their [uploading artifacts doc](https://docs.travis-ci.com/user/uploading-artifacts/).
|
||||
**Understanding when a screenshot happens**
|
||||
|
||||
## Understanding when a screenshot happens
|
||||
Taking a screenshot is an asynchronous action that takes around `100ms` to complete. By the time the screenshot is taken, it's possible something in your application may have changed. It's important to realize that the screenshot may not reflect 100% of what your application looked like when the command was issued.
|
||||
|
||||
Taking a screenshot is an asynchronous action which takes around `100ms` to complete. By the time the screenshot is taken it's possible something in your application may have changed. It's important to realize that the screenshot may not reflect 100% of what your application looked like when the command was issued.
|
||||
|
||||
For example - say this command times outs `cy.get("#element")`. This causes your test to fail. We'll then take a screenshot when the test fails but it's possible something in your application changes within the `100ms` timeframe. Hypothetically your app could render the element you were searching for. When this happens the screenshot may provide confusing results. It's unlikely but theoretically possible.
|
||||
|
||||
## No Command Log scrolling during screenshots
|
||||
|
||||
Currently you may not be able to see the Command Log at the exact test you took the screenshot due to the view not scrolling when the screenshot is taken.
|
||||
For example - say a command we wrote times outs: `cy.get('#element')`. This causes your test to fail. Cypress then takes a screenshot when the test fails, but it's possible something in your application changed within the `100ms` timeframe. Hypothetically your app could render the element you were searching for. When this happens the screenshot may provide confusing results. It's unlikely, but theoretically possible.
|
||||
|
||||
# Command Log
|
||||
|
||||
## Take a screenshot with a specific filename
|
||||
**Take a screenshot with a specific filename**
|
||||
|
||||
```javascript
|
||||
cy.screenshot("my-image")
|
||||
cy.screenshot('my-image')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -97,3 +111,7 @@ The commands above will display in the command log as:
|
||||
When clicking on `screenshot` within the command log, the console outputs the following:
|
||||
|
||||
<img width="667" alt="screen shot 2016-06-13 at 10 46 15 am" src="https://cloud.githubusercontent.com/assets/1271364/16012081/ded22a2e-3155-11e6-8303-0f1ec64e209b.png">
|
||||
|
||||
# See also
|
||||
|
||||
- [Cypress Dashboard](https://on.cypress.io/dashboard)
|
||||
|
||||
@@ -6,20 +6,36 @@ description: ''
|
||||
|
||||
Scroll an element into view.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the element that was scrolled into view |
|
||||
| **Timeout** | `cy.scrollIntoView` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
|
||||
# [cy.scrollIntoView()](#usage)
|
||||
# Syntax
|
||||
|
||||
Scroll to the element found in the previous command into view.
|
||||
```javascript
|
||||
.scrollIntoView()
|
||||
.scrollIntoView(options)
|
||||
```
|
||||
|
||||
# Options
|
||||
## Usage
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.scrollIntoView`.
|
||||
`.scrollIntoView()` requires being chained off another cy command that *yields* a DOM element.
|
||||
|
||||
**[cy.scrollIntoView( *options* )](#options-usage)**
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.get('footer').scrollIntoView() // Scrolls 'footer' into view
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.scrollIntoView('footer') // Errors, cannot be chained off 'cy'
|
||||
cy.window().scrollIntoView() // Errors, 'window' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.scrollIntoView`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
@@ -29,16 +45,25 @@ Option | Default | Notes
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the scroll
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
# Options Usage
|
||||
`.scrollIntoView()` yields the DOM element that was scrolled into view.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.scrollIntoView()` will continue to scroll the element into view for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
# Notes
|
||||
|
||||
## Snapshots
|
||||
**Snapshots do not reflect scroll behavior**
|
||||
|
||||
*Cypress does not reflect the accurate scroll positions of any elements within snapshots.* If you want to see the actual scrolling behavior in action, we recommend using [`cy.pause()`](https://on.cypress.io/api/pause) to walk through each command or [watching the video of the test run](#https://on.cypress.io/guides/runs#videos).
|
||||
|
||||
|
||||
# Command Log
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [scrollTo](https://on.cypress.io/api/scrollto)
|
||||
|
||||
@@ -4,35 +4,53 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Scroll to a specific position in the window or in the element found in the previous command. The DOM element or window must be in a "scrollable" state prior to the scroll happening.
|
||||
Scroll to a specific position.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the window or DOM element that was scrolled |
|
||||
| **Timeout** | `cy.scrollTo` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.scrollTo( *position* )](#position-usage)
|
||||
```javascript
|
||||
cy.scrollTo(position)
|
||||
cy.scrollTo(x, y)
|
||||
cy.scrollTo(position, options)
|
||||
cy.scrollTo(x, y, options)
|
||||
```
|
||||
|
||||
Scroll to a specific position in the window or in the element found in the previous command. Valid positions are `topLeft`, `top`, `topRight`, `left`, `center`, `right`, `bottomLeft`, `bottom`, and `bottomRight`.
|
||||
## Usage
|
||||
|
||||
`.scrollTo()` can be chained off of `cy` to scroll to a position in the window or chained off another cy command that *yields* a DOM element - limiting scrolling to it's yielded element.
|
||||
|
||||
```javascript
|
||||
cy.scrollTo(0, 500) // Scroll the window 500px down
|
||||
cy.get('.sidebar').scrollTo('bottom') // Scroll 'sidebar' to it's bottom
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.title().scrollTo('My App') // Errors, 'title' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
|
||||
**{% fa fa-angle-right %} position** ***(String)***
|
||||
|
||||
Scrolls the window or element to the specified position. Valid positions are `topLeft`, `top`, `topRight`, `left`, `center`, `right`, `bottomLeft`, `bottom`, and `bottomRight`.
|
||||
|
||||

|
||||
|
||||
# [cy.scrollTo( *x*, *y* )](#coordinate-usage)
|
||||
**{% fa fa-angle-right %} x** ***(Number, String)***
|
||||
|
||||
You can pass an `x` and `y` coordinate in pixels which will calculate the distance from the top left corner of the element and scroll to the calculated coordinate. The coordinates can be a number or a string with 'px'.
|
||||
The distance in pixels from element's left or percentage of the element's width to scroll to.
|
||||
|
||||
# [cy.scrollTo( *width %*, *height %* )](#percentage-usage)
|
||||
**{% fa fa-angle-right %} y** ***(Number, String)***
|
||||
|
||||
You can pass a string with the percentage of the element's width and height to scroll to that position.
|
||||
The distance in pixels from element's top or percentage of the element's height to scroll to.
|
||||
|
||||
# Options
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.scrollTo`.
|
||||
|
||||
**[cy.scrollTo( *position*, *options* )](#options-usage)**
|
||||
**[cy.scrollTo( *x*, *y*, *options* )](#options-usage)**
|
||||
**[cy.scrollTo( *width %*, *height %*, *options* )](#options-usage)**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`duration` | `0` | Scrolls over the duration (in ms)
|
||||
@@ -40,69 +58,77 @@ Option | Default | Notes
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the scroll
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Position Usage
|
||||
## Yields
|
||||
|
||||
## Scroll to the bottom of the window
|
||||
`.scrollTo()` yields the window or DOM element that was scrolled.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.scrollTo()` will wait until the window or element is in a 'scrollable' state for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's options
|
||||
|
||||
# Examples
|
||||
|
||||
## Position
|
||||
|
||||
**Scroll to the bottom of the window**
|
||||
|
||||
```javascript
|
||||
cy.scrollTo("bottom")
|
||||
cy.scrollTo('bottom')
|
||||
```
|
||||
|
||||
## Scroll to the center of the list
|
||||
**Scroll to the center of the list**
|
||||
|
||||
```javascript
|
||||
cy.get("#movies-list").scrollTo('center')
|
||||
cy.get('#movies-list').scrollTo('center')
|
||||
```
|
||||
|
||||
# Coordinate Usage
|
||||
## Coordinates
|
||||
|
||||
## Scroll 500px down the list
|
||||
**Scroll 500px down the list**
|
||||
|
||||
```javascript
|
||||
cy.get("#infinite-scroll-list").scrollTo(0, 500)
|
||||
cy.get('#infinite-scroll-list').scrollTo(0, 500)
|
||||
```
|
||||
|
||||
## Scroll the window 500px to the right
|
||||
**Scroll the window 500px to the right**
|
||||
|
||||
```javascript
|
||||
cy.scrollTo("500px")
|
||||
cy.scrollTo('500px')
|
||||
```
|
||||
|
||||
# Percentage Usage
|
||||
|
||||
## Scroll 25% down the element
|
||||
**Scroll 25% down the element's height**
|
||||
|
||||
```javascript
|
||||
cy.get(".user-photo").scrollTo('0%', '25%')
|
||||
cy.get('.user-photo').scrollTo('0%', '25%')
|
||||
```
|
||||
|
||||
# Options Usage
|
||||
## Options
|
||||
|
||||
## Use linear easing animation to scroll
|
||||
**Use linear easing animation to scroll**
|
||||
|
||||
```javascript
|
||||
cy.get(".documentation").scrollTo('top', { easing: 'linear'} )
|
||||
cy.get('.documentation').scrollTo('top', { easing: 'linear'} )
|
||||
```
|
||||
|
||||
## Scroll to the right over 2000ms
|
||||
**Scroll to the right over 2000ms**
|
||||
|
||||
```javascript
|
||||
cy.get("#slider").scrollTo('right', { duration: 2000} )
|
||||
cy.get('#slider').scrollTo('right', { duration: 2000} )
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
## Snapshots
|
||||
**Snapshots do not reflect scroll behavior**
|
||||
|
||||
**Cypress does not reflect the accurate scroll positions of any elements within snapshots.** If you want to see the actual scrolling behavior in action, we recommend using [`cy.pause()`](https://on.cypress.io/api/pause) to walk through each command or [watching the video of the test run](#https://on.cypress.io/guides/runs#videos).
|
||||
*Cypress does not reflect the accurate scroll positions of any elements within snapshots.* If you want to see the actual scrolling behavior in action, we recommend using [`cy.pause()`](https://on.cypress.io/api/pause) to walk through each command or [watching the video of the test run](#https://on.cypress.io/guides/runs#videos).
|
||||
|
||||
# Command Log
|
||||
|
||||
## Scroll to the bottom of the window then scroll the element to the "right"
|
||||
**Scroll to the bottom of the window then scroll the element to the "right"**
|
||||
|
||||
```javascript
|
||||
cy.scrollTo("bottom")
|
||||
cy.get("#scrollable-horizontal").scrollTo("right")
|
||||
cy.scrollTo('bottom')
|
||||
cy.get('#scrollable-horizontal').scrollTo('right')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -113,6 +139,6 @@ When clicking on `scrollTo` within the command log, the console outputs the foll
|
||||
|
||||
<img width="788" alt="screen shot 2017-04-14 at 12 32 16 pm" src="https://cloud.githubusercontent.com/assets/1271364/25049182/6e07211a-210e-11e7-9419-b57f3e08a608.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [scrollIntoView](https://on.cypress.io/api/scrollintoview)
|
||||
|
||||
@@ -6,36 +6,46 @@ description: ''
|
||||
|
||||
Select an option within a `<select>` DOM element.
|
||||
|
||||
**The following events are fired during select:** `mousedown`, `focus`, `mouseup`, `click`
|
||||
# Syntax
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.select` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's [options](#options). |
|
||||
```javascript
|
||||
.select(value)
|
||||
.select(values)
|
||||
.select(value, options)
|
||||
.select(values, options)
|
||||
```
|
||||
|
||||
# [cy.select( *text* )](#text-usage)
|
||||
## Usage
|
||||
|
||||
Select an option within a `<select>` element based on the text content of the option.
|
||||
`.select()` requires being chained off another cy command that *yields* a `<select>` DOM element.
|
||||
|
||||
# [cy.select( *value* )](#value-usage)
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
Select an option within a `<select>` element based on the value of the option.
|
||||
```javascript
|
||||
cy.get('select').select('user-1') // Select the 'user-1' option
|
||||
```
|
||||
|
||||
# [cy.select( *texts* )](#texts-usage)
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
Select multiple options within a `<select>` element based on the text of the option.
|
||||
```javascript
|
||||
cy.select('John Adams') // Errors, cannot be chained off 'cy'
|
||||
cy.location().select() // Errors, 'location' does not yield <select> element
|
||||
```
|
||||
|
||||
# [cy.select( *values* )](#values-usage)
|
||||
|
||||
Select multiple options within a `<select>` element based on the value of the option.
|
||||
## Arguments
|
||||
|
||||
# Options
|
||||
**{% fa fa-angle-right %} value** ***(String)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.select`.
|
||||
The `value` or text content of the option to be selected.
|
||||
|
||||
**cy.select( *text*, *options* )**
|
||||
**cy.select( *value*, *options* )**
|
||||
**cy.select( *array*, *options* )**
|
||||
**{% fa fa-angle-right %} values** ***(Array)***
|
||||
|
||||
An array of `values` or text contents of the options to be selected.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.select()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
@@ -44,9 +54,20 @@ Option | Default | Notes
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the select
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Text Usage
|
||||
|
||||
## Select the option with the text `apples`
|
||||
## Yields
|
||||
|
||||
`.select()` yields the new DOM elements selected.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.select()` will continue to select the options for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Text Content
|
||||
|
||||
**Select the option with the text `apples`**
|
||||
|
||||
```html
|
||||
<select>
|
||||
@@ -57,13 +78,13 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
// returns <option value="456">apples</option>
|
||||
cy.get("select").select("apples")
|
||||
// yields <option value="456">apples</option>
|
||||
cy.get('select').select('apples')
|
||||
```
|
||||
|
||||
# Value Usage
|
||||
## Value
|
||||
|
||||
## Select the option with the value "456"
|
||||
**Select the option with the value "456"**
|
||||
|
||||
```html
|
||||
<select>
|
||||
@@ -74,13 +95,13 @@ cy.get("select").select("apples")
|
||||
```
|
||||
|
||||
```javascript
|
||||
// returns <option value="456">apples</option>
|
||||
cy.get("select").select("456")
|
||||
// yields <option value="456">apples</option>
|
||||
cy.get('select').select('456')
|
||||
```
|
||||
|
||||
# Texts Usage
|
||||
## Select multiple options
|
||||
|
||||
## Select the options with the texts "apples" and "bananas"
|
||||
**Select the options with the texts "apples" and "bananas"**
|
||||
|
||||
```html
|
||||
<select multiple>
|
||||
@@ -91,12 +112,10 @@ cy.get("select").select("456")
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy.get("select").select(["apples", "bananas"])
|
||||
cy.get('select').select(['apples', 'bananas'])
|
||||
```
|
||||
|
||||
# Values Usage
|
||||
|
||||
## Select the options with the values "456" and "457"
|
||||
**Select the options with the values "456" and "457"**
|
||||
|
||||
```html
|
||||
<select multiple>
|
||||
@@ -107,15 +126,15 @@ cy.get("select").select(["apples", "bananas"])
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy.get("select").select(["456", "457"])
|
||||
cy.get('select').select(['456', '457'])
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Select the option with the text "Homer Simpson"
|
||||
**Select the option with the text "Homer Simpson"**
|
||||
|
||||
```javascript
|
||||
cy.get("select").select("Homer Simpson")
|
||||
cy.get('select').select('Homer Simpson')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -126,6 +145,6 @@ When clicking on `select` within the command log, the console outputs the follow
|
||||
|
||||
<img width="560" alt="screen shot 2015-11-29 at 1 17 45 pm" src="https://cloud.githubusercontent.com/assets/1271364/11459045/a6b3bde2-969b-11e5-9357-272ea9684987.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [click](https://on.cypress.io/api/click)
|
||||
|
||||
@@ -4,107 +4,110 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Start a server to begin routing responses to `.route()` and `.request()`.
|
||||
|
||||
{% note info New to Cypress? %}
|
||||
[Read about Network Requests first.](https://on.cypress.io/guides/network-requests-xhr)
|
||||
{% endnote %}
|
||||
|
||||
Use `cy.server` to control the behavior of requests and responses.
|
||||
# Syntax
|
||||
|
||||
# [cy.server()](#default-usage)
|
||||
```javascript
|
||||
cy.server()
|
||||
cy.server(options)
|
||||
```
|
||||
|
||||
Start a server to begin routing responses to your requests.
|
||||
## Usage
|
||||
|
||||
# Options
|
||||
`.server()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.server`.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
**[cy.server(*options* )](#options-usage)**
|
||||
```javascript
|
||||
cy.server()
|
||||
```
|
||||
|
||||
`cy.server` takes options that are used for 2 different purposes:
|
||||
## Arguments
|
||||
|
||||
1. As defaults which are merged into [`cy.route`](https://on.cypress.io/api/route).
|
||||
**{% 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
|
||||
|
||||
1. As defaults that are merged into [`.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)
|
||||
***The following options are merged in as default options to [`.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
|
||||
`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:
|
||||
***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`.
|
||||
`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 `.js`, `.jsx`, `.html`, and `.css`
|
||||
`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.
|
||||
|
||||
# Default Usage
|
||||
## Yields
|
||||
|
||||
## Start a server
|
||||
`.server()` yields the Cypress server instance.
|
||||
|
||||
## Timeout
|
||||
|
||||
|
||||
# Examples
|
||||
|
||||
## Start Server
|
||||
|
||||
**After starting a server:**
|
||||
|
||||
- Any request that does not match a [`.route()`](https://on.cypress.io/api/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.
|
||||
|
||||
```javascript
|
||||
cy.server()
|
||||
```
|
||||
|
||||
**After starting a server:**
|
||||
## Options
|
||||
|
||||
- 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.
|
||||
## Change defaults for [`.route()`](https://on.cypress.io/api/route)
|
||||
|
||||
# Options Usage
|
||||
By default [`cy.route`](https://on.cypress.io/api/route) inherits some of its options from `cy.server()`.
|
||||
|
||||
## 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
|
||||
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()`](https://on.cypress.io/api/route).
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server({
|
||||
method: "POST",
|
||||
delay: 1000,
|
||||
status: 422,
|
||||
response: {}
|
||||
})
|
||||
|
||||
// our route command will now inherit its options
|
||||
// from the server. anything we pass specifically
|
||||
// to route will override the defaults.
|
||||
//
|
||||
// in this example our matching requests will
|
||||
// be delayed 1000ms and have a status of 422
|
||||
// but its response will be what we set in route
|
||||
.route(/users/, {errors: "Name cannot be blank"})
|
||||
cy.server({
|
||||
method: 'POST',
|
||||
delay: 1000,
|
||||
status: 422,
|
||||
response: {}
|
||||
})
|
||||
|
||||
cy.route('/users/', {errors: 'Name cannot be blank'})
|
||||
```
|
||||
|
||||
## Change the default delay for all routes
|
||||
**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.
|
||||
|
||||
```javascript
|
||||
// delay each response 1500ms
|
||||
// delay each route's response 1500ms
|
||||
cy.server({delay: 1500})
|
||||
```
|
||||
|
||||
## Prevent sending 404's to unmatched requests
|
||||
**Prevent sending 404's to unmatched requests**
|
||||
|
||||
If you'd like Cypress to automatically send requests that do *NOT* match routes the following:
|
||||
|
||||
@@ -112,49 +115,44 @@ Status | Body | Headers
|
||||
--- | --- | ---
|
||||
`404` | "" | `null`
|
||||
|
||||
Simply set `{force404: true}`
|
||||
Simply set `force404` to `true`.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server({force404: true})
|
||||
.route(/activities/, "fixture:activities.json")
|
||||
cy.server({ force404: true })
|
||||
cy.route('/activities/**', 'fixture:activities.json')
|
||||
```
|
||||
|
||||
```javascript
|
||||
|
||||
// Application Code
|
||||
|
||||
$(function(){
|
||||
$.get("/activities")
|
||||
$.get('/activities')
|
||||
|
||||
// this will be sent back 404 since it
|
||||
// does not match any of the cy.routes
|
||||
$.getJSON("/users.json")
|
||||
$.getJSON('/users.json')
|
||||
})
|
||||
```
|
||||
|
||||
## Change the default response headers for all routes
|
||||
**Change the default response headers for all routes**
|
||||
|
||||
When you stub requests, you can automatically control their response headers.
|
||||
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've stubbed
|
||||
Cypress automatically sets `Content-Length` and `Content-Type` based on the response body you stub.
|
||||
{% endnote %}
|
||||
|
||||
This is useful when you want to send back meta data in the headers, such as **pagination** or **token** information.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server({
|
||||
cy.server({
|
||||
headers: {
|
||||
"x-token": "abc-123-foo-bar"
|
||||
'x-token': 'abc-123-foo-bar'
|
||||
}
|
||||
})
|
||||
.route("GET", "/users/1", {id: 1, name: "Amanda"}).as("getUser")
|
||||
.visit("/users/1/profile")
|
||||
.wait("@getUser")
|
||||
.its("responseHeaders")
|
||||
.should("have.property", "x-token", "abc-123-foo-bar") // true
|
||||
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
|
||||
```
|
||||
|
||||
```javascript
|
||||
@@ -163,32 +161,31 @@ cy
|
||||
// lets use the native XHR object
|
||||
var xhr = new XMLHttpRequest
|
||||
|
||||
xhr.open("GET", "/users/1")
|
||||
xhr.open('GET', '/users/1')
|
||||
|
||||
xhr.onload = function(){
|
||||
var token = this.getResponseHeader("x-token")
|
||||
var token = this.getResponseHeader('x-token')
|
||||
console.log(token) // => abc-123-foo-bar
|
||||
}
|
||||
|
||||
xhr.send()
|
||||
|
||||
```
|
||||
|
||||
## Change the default whitelisting
|
||||
**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`.
|
||||
`.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 `cy.route`).
|
||||
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()`](https://on.cypress.io/api/route)).
|
||||
|
||||
The idea is that we never went to interfere with static assets that are fetched via AJAX.
|
||||
The idea is that we never want to interfere with static assets that are fetched via AJAX.
|
||||
|
||||
The default whitelist function is:
|
||||
The default whitelist function in Cypress is:
|
||||
|
||||
```javascript
|
||||
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)
|
||||
xhr.method === 'GET' && /\.(jsx?|html|css)(\?.*)?$/.test(xhr.url)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -204,46 +201,38 @@ cy.server({
|
||||
})
|
||||
```
|
||||
|
||||
If you would like to change the default option for **ALL** `cy.server` you [can change this option permanently](#permanently-override-default-server-options).
|
||||
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
|
||||
**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.
|
||||
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.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route("POST", /users/, {}).as("createUser")
|
||||
cy.server()
|
||||
cy.route('POST', '/users', {}).as('createUser')
|
||||
|
||||
...
|
||||
|
||||
// this now 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
|
||||
.server({enable: false})
|
||||
cy.server({enable: false})
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
## Server persists until the next test runs
|
||||
**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.
|
||||
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
|
||||
**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`.
|
||||
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`
|
||||
**Server can be started before you [`cy.visit`](https://on.cypress.io/api/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
|
||||
# See also
|
||||
|
||||
- [route](https://on.cypress.io/api/route)
|
||||
- [wait](https://on.cypress.io/api/wait)
|
||||
|
||||
@@ -6,20 +6,36 @@ description: ''
|
||||
|
||||
Set a browser cookie.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | a cookie object |
|
||||
| **Timeout** | `cy.setCookie` will wait up for the duration of [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the automation server to process this command. |
|
||||
# Syntax
|
||||
|
||||
# [cy.setCookie( *name*, *value* )](#usage)
|
||||
```javascript
|
||||
cy.setCookie(name, value)
|
||||
cy.setCookie(name, value, options)
|
||||
```
|
||||
|
||||
Sets a browser cookie.
|
||||
## Usage
|
||||
|
||||
# Options
|
||||
`cy.setCookie()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.setCookie`.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
**[cy.setCookie( *name*, *value*, *options* )](#options-usage)**
|
||||
```javascript
|
||||
cy.setCookie('auth_key', '123key')
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} name** ***(String)***
|
||||
|
||||
The name of the cookie to set.
|
||||
|
||||
**{% fa fa-angle-right %} value** ***(String)***
|
||||
|
||||
The value of the cookie to set.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.setCookie()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
@@ -28,12 +44,30 @@ Option | Default | Notes
|
||||
`secure` | `false` | whether the cookie is a secure cookie
|
||||
`httpOnly` | `false` | whether the cookie is an HTTP only cookie
|
||||
`expiry` | 20 years into the future | when the cookie expires, specified in seconds since [Unix Epoch](https://en.wikipedia.org/wiki/Unix_time).
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the `cy.setCookie` command to be processed
|
||||
`timeout` | [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the `cy.setCookie()` command to be processed
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Set a cookie
|
||||
`.setCookie()` yields a cookie object literal with the following properties:
|
||||
|
||||
- `name`
|
||||
- `value`
|
||||
- `path`
|
||||
- `domain`
|
||||
- `httpOnly`
|
||||
- `secure`
|
||||
- `expiry`
|
||||
|
||||
## Timeout
|
||||
|
||||
`.setCookie()` will wait up for the duration of [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the automation server to process this command.
|
||||
|
||||
# Examples
|
||||
|
||||
## Set Value
|
||||
|
||||
**Set a cookie**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
@@ -44,7 +78,7 @@ cy
|
||||
|
||||
# Command Log
|
||||
|
||||
## Get cookie
|
||||
**Set a cookie**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
@@ -61,7 +95,7 @@ When clicking on `setCookie` within the command log, the console outputs the fol
|
||||
|
||||

|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [clearCookie](https://on.cypress.io/api/clearcookie)
|
||||
- [clearCookies](https://on.cypress.io/api/clearcookies)
|
||||
|
||||
@@ -4,85 +4,146 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Make an assertion.
|
||||
|
||||
{% note info %}
|
||||
An alias of [`.and()`](https://on.cypress.io/api/and)
|
||||
{% endnote %}
|
||||
|
||||
{% note info New to Cypress? %}
|
||||
[Read about making assertions first.](https://on.cypress.io/guides/making-assertions)
|
||||
{% endnote %}
|
||||
|
||||
`cy.should` makes assertions about the current subject.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the current subject but (in some cases) a new subject |
|
||||
| **Timeout** | the assertion will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
|
||||
# [cy.should( *chainers* )](#chainers-usage)
|
||||
|
||||
Implicitly assert about the current subject.
|
||||
|
||||
# [cy.should( *chainers*, *value* )](#chainers-with-value-usage)
|
||||
|
||||
Implicitly assert a value about the current subject. Returns the existing current subject (usually). Some chai methods and chai-jQuery methods return a new (different) subject for chain-ability.
|
||||
|
||||
# [cy.should( *chainers*, *method*, *value* )](#chainers-with-method-and-value-usage)
|
||||
|
||||
Implicitly assert about the subject by calling a method and providing a value to that method.
|
||||
|
||||
# [cy.should( *function* )](#function-usage)
|
||||
|
||||
Pass a function that can have any number of explicit assertions within it. Does not change the subject. Whatever was passed to the function is what is returned.
|
||||
|
||||
# Chainers Usage
|
||||
|
||||
## Assert the checkbox is disabled
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
cy.get(":checkbox").should("be.disabled")
|
||||
.should(chainers)
|
||||
.should(chainers, value)
|
||||
.should(chainers, method, value)
|
||||
.should(function() {})
|
||||
```
|
||||
|
||||
## The current subject is returned
|
||||
|
||||
## Usage
|
||||
|
||||
`.should()` requires being chained off another cy command.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.get("option:first").should("be.selected").then(function($option)){
|
||||
// $option is still the current subject
|
||||
cy.get('.error').should('be.empty') // Yields '.error' el
|
||||
cy.contains('Login').should('be.visible') // Yields el containing Login
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.should('eq', '42') // Errors, cannot be chained off 'cy'
|
||||
```
|
||||
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} chainers** ***(String)***
|
||||
|
||||
Chainers that come from [Chai](https://on.cypress.io/guides/bundled-tools#chai) or [Chai-jQuery](https://on.cypress.io/guides/bundled-tools#chai-jquery)
|
||||
|
||||
**{% fa fa-angle-right %} value** ***(String)***
|
||||
|
||||
Value to assert against chainer.
|
||||
|
||||
**{% fa fa-angle-right %} method** ***(String)***
|
||||
|
||||
A method to be called on the chainer.
|
||||
|
||||
**{% fa fa-angle-right %} function** ***(Function)***
|
||||
|
||||
Pass a function that can have any number of explicit assertions within it. Whatever was passed to the function is what is yielded.
|
||||
|
||||
|
||||
## Yields
|
||||
|
||||
In most cases, `.should()` yields the previous cy command's yield.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get('nav') // yields <nav>
|
||||
.should('be.visible') // yields <nav>
|
||||
```
|
||||
Although some chainers change what is yielded. In the example below, the second `.should()` yields the String 'sans-serif' because the chainer `have.css, 'font-family'` yields a string.
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get('nav') // yields <nav>
|
||||
.should('be.visible') // yields <nav>
|
||||
.should('have.css', 'font-family') // yields 'sans-serif'
|
||||
```
|
||||
|
||||
## Timeout
|
||||
|
||||
`.should` will continue to retry the assertion to the duration of the previous cy commands `timeout` or the `defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
```javascript
|
||||
cy.get('input', {timeout: 10000}).should('have.value', '10')
|
||||
↲
|
||||
// timeout here will be passed down to the '.should()'
|
||||
// and it will retry for up to 10 secs
|
||||
```
|
||||
|
||||
# Examples
|
||||
|
||||
## Chainers
|
||||
|
||||
**Assert the checkbox is disabled**
|
||||
|
||||
```javascript
|
||||
cy.get(':checkbox').should('be.disabled')
|
||||
```
|
||||
|
||||
**The current DOM element is yielded**
|
||||
|
||||
```javascript
|
||||
cy.get('option:first').should('be.selected').then(function($option)){
|
||||
// $option is yielded
|
||||
})
|
||||
```
|
||||
|
||||
# Chainers with Value Usage
|
||||
## Chainers with Value
|
||||
|
||||
## Assert the class is 'form-horizontal'
|
||||
**Assert the class is 'form-horizontal'**
|
||||
|
||||
```javascript
|
||||
cy.get("form").should("have.class", "form-horizontal")
|
||||
cy.get('form').should('have.class', 'form-horizontal')
|
||||
```
|
||||
|
||||
## Assert the value is not 'foo'
|
||||
**Assert the value is not 'foo'**
|
||||
|
||||
```javascript
|
||||
cy.get("input").should("not.have.value", "foo")
|
||||
cy.get('input').should('not.have.value', 'foo')
|
||||
```
|
||||
|
||||
## The current subject is returned
|
||||
**The current subject is yielded**
|
||||
|
||||
```javascript
|
||||
cy.get("button").should("have.id", "new-user").then(function($button){
|
||||
// $button is still the current subject
|
||||
cy.get('button').should('have.id', 'new-user').then(function($button){
|
||||
// $button is yielded
|
||||
})
|
||||
```
|
||||
|
||||
# Chainers with Method and Value Usage
|
||||
## Chainers with Method and Value
|
||||
|
||||
## Assert the href is equal to '/users'
|
||||
**Assert the href is equal to '/users'**
|
||||
|
||||
```javascript
|
||||
// have.attr comes from chai-jquery
|
||||
cy.get("#header a").should("have.attr", "href", "/users")
|
||||
cy.get('#header a').should('have.attr', 'href', '/users')
|
||||
```
|
||||
|
||||
# Function Usage
|
||||
## Function
|
||||
|
||||
## Verify length, content, and classes from multiple `<p>`
|
||||
**Verify length, content, and classes from multiple `<p>`**
|
||||
|
||||
Passing a function to `should` enables you to assert on arbitrary subjects. This gives you the opportunity to *massage* what you'd like to assert on.
|
||||
Passing a function to `.should()` enables you to assert on the yielded subject. This gives you the opportunity to *massage* what you'd like to assert on.
|
||||
|
||||
Just be sure *not* to include any code that has side effects in your callback function.
|
||||
|
||||
@@ -98,139 +159,110 @@ The callback function will be retried over and over again until no assertions wi
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("p")
|
||||
.get('p')
|
||||
.should(function($p){
|
||||
// should have found 3 elements
|
||||
expect($p).to.have.length(3)
|
||||
|
||||
// make sure the first contains some text content
|
||||
expect($p.first()).to.contain("Hello World")
|
||||
expect($p.first()).to.contain('Hello World')
|
||||
|
||||
// use jquery's map to grab all of their classes
|
||||
// jquery's map returns a new jquery object
|
||||
var classes = $p.map(function(i, el){
|
||||
return cy.$(el).attr("class")
|
||||
return cy.$(el).attr('class')
|
||||
})
|
||||
|
||||
// call classes.get() to make this a plain array
|
||||
expect(classes.get()).to.deep.eq([
|
||||
"text-primary",
|
||||
"text-danger",
|
||||
"text-default"
|
||||
'text-primary',
|
||||
'text-danger',
|
||||
'text-default'
|
||||
])
|
||||
})
|
||||
```
|
||||
|
||||
## Using a callback function will not change the subject
|
||||
**Assert explicitly within `.should()`**
|
||||
|
||||
```html
|
||||
<div id="todos">
|
||||
<li>Walk the dog</li>
|
||||
<li>Feed the cat</li>
|
||||
<li>Write JavaScript</li>
|
||||
</div>
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy.get("#todos li").should(function($lis){
|
||||
expect($lis).to.have.length(3)
|
||||
expect($lis.eq(0)).to.contain("Walk the dog")
|
||||
expect($lis.eq(1)).to.contain("Feed the cat")
|
||||
expect($lis.eq(2)).to.contain("Write JavaScript")
|
||||
})
|
||||
```
|
||||
|
||||
{% note warning %}
|
||||
Any errors raised by failed assertions will immediately bubble up and cause the test to fail.
|
||||
{% endnote %}
|
||||
|
||||
**Using a callback function will not change the subject**
|
||||
|
||||
Whatever is returned in the function is ignored. Cypress always forces the command to yield the value from the previous cy command's yield (which in the example below is `<button>`)
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("button").should(function($button){
|
||||
// whatever we return here is ignored
|
||||
// as Cypress will always force the return
|
||||
// value for future commands to be the same
|
||||
// as the previous subject which is <button>
|
||||
|
||||
expect({foo: "bar"}).to.deep.eq({foo: "bar"})
|
||||
|
||||
// whatever the return value (if any) is ignored
|
||||
return {foo: "bar"}
|
||||
.get('button').should(function($button){
|
||||
expect({foo: 'bar'}).to.deep.eq({foo: 'bar'})
|
||||
return {foo: 'bar'} // return is ignored, .should() yields <button>
|
||||
})
|
||||
|
||||
.then(function($button){
|
||||
// $button === <button>
|
||||
// the subject is unchanged no matter what was returned
|
||||
// do anything we want with <button>
|
||||
})
|
||||
```
|
||||
|
||||
# Multiple Assertions
|
||||
## Multiple Assertions
|
||||
|
||||
## Chaining multiple assertions
|
||||
**Chaining multiple assertions**
|
||||
|
||||
Cypress makes it easy to chain assertions together.
|
||||
|
||||
In this example we use [`cy.and`](https://on.cypress.io/api/and) which is identical to `should`.
|
||||
In this example we use [`.and()`](https://on.cypress.io/api/and) which is identical to `.should()`.
|
||||
|
||||
```javascript
|
||||
// our subject is not changed by our first assertion,
|
||||
// so we can continue to use DOM based assertions
|
||||
cy.get("option:first").should("be.selected").and("have.value", "Metallica")
|
||||
cy.get('option:first').should('be.selected').and('have.value', 'Metallica')
|
||||
```
|
||||
|
||||
## Assertions that change the subject
|
||||
|
||||
Sometimes using a specific chainer will automatically change the assertion subject.
|
||||
|
||||
For instance in `chai`, the method [`have.property("...")`](http://chaijs.com/api/bdd/) will automatically change the subject.
|
||||
|
||||
Additionally in [`Chai-jQuery`](https://github.com/chaijs/chai-jquery#attrname-value), the methods: `attr`, `prop`, `css`, and `data` also change the subject.
|
||||
|
||||
This allows you to utilize other `chainer` methods such as `match` when making assertions about values.
|
||||
|
||||
```javascript
|
||||
// in this example our subject changed to the string 'sans-serif' because
|
||||
// have.css("font-family") returned a string instead of the <body> element
|
||||
cy
|
||||
// subject is <body>
|
||||
.get("body")
|
||||
|
||||
// subject changes to the string return value of 'font-family'
|
||||
.should("have.css", "font-family")
|
||||
|
||||
// use match to assert the string matches a regular expression
|
||||
.and("match", /sans-serif/)
|
||||
```
|
||||
|
||||
```javascript
|
||||
// in this example our subject changed to the string '/users' because
|
||||
// have.attr, href, /users returned a string instead of the <a> element
|
||||
cy
|
||||
// subject is <a>
|
||||
.get("a")
|
||||
|
||||
// subject changes to the string 'users'
|
||||
.should("have.attr", "href", "/users")
|
||||
```
|
||||
|
||||
# Automatic Retry Support
|
||||
|
||||
Cypress won't resolve your commands until all of its assertions pass.
|
||||
|
||||
## Wait until the assertions pass
|
||||
|
||||
Cypress won't resolve your commands until all of its assertions pass.
|
||||
|
||||
```javascript
|
||||
// Application Code
|
||||
$("button").click(function(){
|
||||
$('button').click(function(){
|
||||
$button = $(this)
|
||||
|
||||
setTimeout(function(){
|
||||
$button.removeClass("inactive").addClass("active")
|
||||
$button.removeClass('inactive').addClass('active')
|
||||
}, 1000)
|
||||
})
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("button")
|
||||
.get('button')
|
||||
.click()
|
||||
.should("have.class", "active")
|
||||
.and("not.have.class", "inactive")
|
||||
.should('have.class', 'active')
|
||||
.and('not.have.class', 'inactive')
|
||||
```
|
||||
|
||||
You can [read more about how Cypress resolves your assertions](https://on.cypress.io/guides/making-assertions#resolving-assertions) here.
|
||||
|
||||
# Notes
|
||||
|
||||
## What assertions and chainers can I use?
|
||||
|
||||
The chainers that `cy.should` accepts come from:
|
||||
|
||||
* Chai
|
||||
* Chai-jQuery
|
||||
|
||||
A [list of these](https://on.cypress.io/guides/making-assertions#available-assertions) can be found here.
|
||||
|
||||
## How do I know which assertions change the subject and which keep it the same?
|
||||
**How do I know which assertions change the subject and which keep it the same?**
|
||||
|
||||
The chainers that come from [Chai](https://on.cypress.io/guides/bundled-tools#chai) or [Chai-jQuery](https://on.cypress.io/guides/bundled-tools#chai-jquery) will always document what they return.
|
||||
|
||||
@@ -238,40 +270,16 @@ Alternatively, it is very easy to use Cypress itself to figure this out.
|
||||
|
||||
You can [read more about debugging assertions](https://on.cypress.io/guides/making-assertions#debugging-assertions) here.
|
||||
|
||||
## Can I pass options to cy.should()?
|
||||
|
||||
Options passed to the preceding command will be passed through to `cy.should`.
|
||||
|
||||
The following example is an example of increasing the `timeout` of the `cy.should`:
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("input", {timeout: 10000}) // <-- wait up to 10 seconds for this 'input' to be found
|
||||
.should("have.value", "foo") // <-- and to have the value 'foo'
|
||||
.and("have.class", "radio") // <-- and to have the class 'radio'
|
||||
|
||||
.parents("#foo", {timeout: 2000}) // <--
|
||||
.should("not.exist") // <-- wait up to 2 seconds for this element NOT to be found
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy.find("input", {timeout: 10000}).should("have.value", "foo").and("have.class", "radio")
|
||||
↲
|
||||
// adding the timeout here will automatically
|
||||
// flow down to the assertions, and they will
|
||||
// be retried for up to 10 seconds
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Assert that there should be 8 children in a nav
|
||||
**Assert that there should be 8 children in a nav**
|
||||
|
||||
```javascript
|
||||
//
|
||||
cy
|
||||
.get(".left-nav>.nav")
|
||||
.get('.left-nav>.nav')
|
||||
.children()
|
||||
.should("have.length", 8)
|
||||
.should('have.length', 8)
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -282,7 +290,7 @@ When clicking on `assert` within the command log, the console outputs the follow
|
||||
|
||||
<img width="768" alt="screen shot 2015-11-29 at 12 08 45 pm" src="https://cloud.githubusercontent.com/assets/1271364/11458633/08a7b238-9692-11e5-9d5d-620122436bc0.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [and](https://on.cypress.io/api/and)
|
||||
- [Assertions](https://on.cypress.io/guides/making-assertions)
|
||||
|
||||
@@ -4,36 +4,65 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the siblings DOM elements of each element in the set of matched DOM elements.
|
||||
Get sibling DOM elements.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.siblings` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.siblings()](#usage)
|
||||
```javascript
|
||||
.siblings()
|
||||
.siblings(selector)
|
||||
.siblings(options)
|
||||
.siblings(selector, options)
|
||||
```
|
||||
|
||||
Get the siblings of each DOM element in the set of matched DOM elements.
|
||||
## Usage
|
||||
|
||||
# [cy.siblings( *selector* )](#selector-usage)
|
||||
`.siblings()` requires being chained off another cy command that *yields* a DOM element or DOM elements.
|
||||
|
||||
Get the siblings of each DOM element in the set of matched DOM elements filtered by a selector.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# Options
|
||||
```javascript
|
||||
cy.get('td').siblings() // Yield all td's siblings
|
||||
cy.get('li').siblings('.active') // Yield all li's siblings with class '.active'
|
||||
```
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.siblings`.
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
**cy.siblings( *options* )**
|
||||
**cy.siblings( *selector*, *options* )**
|
||||
```javascript
|
||||
cy.siblings('.error') // Errors, cannot be chained off 'cy'
|
||||
cy.location().siblings() // Errors, 'location' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} selector** ***(String selector)***
|
||||
|
||||
A selector used to filter matching DOM elements.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.siblings()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry getting the element
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Get the siblings of each li.
|
||||
`.siblings()` yields the new DOM elements found by the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.siblings()` will continue to look for the sibling element(s) for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
|
||||
|
||||
# Examples
|
||||
|
||||
## Siblings
|
||||
|
||||
**Get the siblings of each li**
|
||||
|
||||
```html
|
||||
<ul>
|
||||
@@ -45,25 +74,25 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
// returns all other li's in list
|
||||
cy.get(".active").siblings()
|
||||
// yields all other li's in list
|
||||
cy.get('.active').siblings()
|
||||
```
|
||||
|
||||
# Selector Usage
|
||||
## Selector
|
||||
|
||||
## Get siblings of element with class `active`.
|
||||
**Get siblings of element with class `active`**
|
||||
|
||||
```javascript
|
||||
// returns <li class="active">Services</li>
|
||||
cy.get("li").siblings(".active")
|
||||
// yields <li class="active">Services</li>
|
||||
cy.get('li').siblings('.active')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Get the siblings of element with class `active`
|
||||
**Get the siblings of element with class `active`**
|
||||
|
||||
```javascript
|
||||
cy.get(".left-nav").find("li.active").siblings()
|
||||
cy.get('.left-nav').find('li.active').siblings()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -74,7 +103,7 @@ When clicking on `siblings` within the command log, the console outputs the foll
|
||||
|
||||
<img width="429" alt="screen shot 2015-11-29 at 12 49 09 pm" src="https://cloud.githubusercontent.com/assets/1271364/11458898/ab940fd2-9697-11e5-96ab-a4c34efa3431.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [prev](https://on.cypress.io/api/prev)
|
||||
- [next](https://on.cypress.io/api/next)
|
||||
|
||||
@@ -4,34 +4,80 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
The spread command allows an expression to be expanded in places where multiple arguments are expected. Similar to [`cy.then`](https://on.cypress.io/api/then), but always expects an array as it's subject.
|
||||
Expand an array into multiple arguments.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the value of the spread |
|
||||
| **Timeout** | *cannot timeout* |
|
||||
{% note info %}
|
||||
Similar of [`.then()`](https://on.cypress.io/api/then), but always expects an array as it's subject.
|
||||
{% endnote %}
|
||||
|
||||
# [cy.spread( *fn* )](#usage)
|
||||
# Syntax
|
||||
|
||||
Expand an array of arguments.
|
||||
```javascript
|
||||
.spread(fn)
|
||||
```
|
||||
|
||||
# Usage
|
||||
## Usage
|
||||
|
||||
## Expand the array of aliased routes
|
||||
`.spread()` requires being chained off another cy command that *yields* an array.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.getCookies.spread(function() {}) // Yield all el's with class '.users'
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.spread(function() {}) // Errors, cannot be chained off 'cy'
|
||||
cy.location().spread() // Errors, 'location' does not yield an array
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} fn** ***(Function)***
|
||||
|
||||
Pass a function that expands the array into it's arguments.
|
||||
|
||||
## Yields
|
||||
|
||||
Whatever was passed to the function is what is yielded.
|
||||
|
||||
## Timeout
|
||||
|
||||
# Examples
|
||||
|
||||
## Aliased Routes
|
||||
|
||||
**Expand the array of aliased routes**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route(/users/).as("getUsers")
|
||||
.route(/activities/).as("getActivities")
|
||||
.route(/comments/).as("getComments")
|
||||
.wait(["@getUsers", "@getActivities", "@getComments"])
|
||||
.route('/users/').as('getUsers')
|
||||
.route('/activities/').as('getActivities')
|
||||
.route('/comments/').as('getComments')
|
||||
.wait(['@getUsers', '@getActivities', '@getComments'])
|
||||
.spread(function(getUsers, getActivities, getComments){
|
||||
// each XHR is now an individual argument
|
||||
})
|
||||
```
|
||||
|
||||
# Related
|
||||
## Cookies
|
||||
|
||||
**Expand the array of cookies**
|
||||
|
||||
```javascript
|
||||
cy.getCookies().spread(function(cookie1, cookie2, cookie3){
|
||||
// each cookie is now an individual argument
|
||||
})
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
**`spread` does *not* log in the command log**
|
||||
|
||||
# See also
|
||||
|
||||
- [then](https://on.cypress.io/api/then)
|
||||
- [wait](https://on.cypress.io/api/wait)
|
||||
|
||||
@@ -4,52 +4,71 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Wrap a method in a spy in order to record calls to the functions and what arguments the function was called with.
|
||||
Wrap a method in a spy in order to record calls to and arguments of the function.
|
||||
|
||||
`cy.spy` returns a [Sinon.js spy](http://sinonjs.org/docs/#spies). All [methods](http://sinonjs.org/docs/#spies-api) found on Sinon.JS spies are supported. `cy.spy` creates spies in a [sandbox](http://sinonjs.org/docs/#sandbox), so all spies created are automatically reset/restored between tests without you having to explicitly reset/restore them.
|
||||
# Syntax
|
||||
|
||||
The main difference between `cy.spy` and [`cy.stub`](https://on.cypress.io/api/stub) is that `cy.spy` does not replace the method, it only wraps it. So, while invocations are recorded, the original method is still called. This can be very useful when testing methods on native browser objects. You can verify a method is being called by your test and still have the original method action invoked.
|
||||
```javascript
|
||||
cy.spy(object, method)
|
||||
```
|
||||
|
||||
Cypress has also built-in [sinon-chai](https://github.com/domenic/sinon-chai) support, so any [assertions](https://github.com/domenic/sinon-chai#assertions) supported by `sinon-chai` can be used without any configuration.
|
||||
## Usage
|
||||
|
||||
`.spy()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.spy(user, 'addFriend')
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} object** ***(Object)***
|
||||
|
||||
The object that has the `method` to be wrapped.
|
||||
|
||||
**{% fa fa-angle-right %} method** ***(String)***
|
||||
|
||||
The name of the `method` on the `object` to be wrapped.
|
||||
|
||||
## Yields
|
||||
|
||||
Unlike most Cypress commands, `cy.spy` is *synchronous* and returns a value (the spy) instead of a Promise-like chain-able object.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the spy |
|
||||
`cy.spy` returns a [Sinon.js spy](http://sinonjs.org/docs/#spies). All [methods](http://sinonjs.org/docs/#spies-api) found on Sinon.JS spies are supported.
|
||||
|
||||
# [cy.spy( *object*, *"method"* )](#usage)
|
||||
## Timeout
|
||||
|
||||
Wraps the `method` on the `object` with a spy and returns the spy. See the [sinon.js spy docs](http://sinonjs.org/docs/#spies) for [methods](http://sinonjs.org/docs/#spies-api) on the spy.
|
||||
# Examples
|
||||
|
||||
# Usage
|
||||
## Spy
|
||||
|
||||
## Wrap a method with a spy
|
||||
**Wrap a method with a spy**
|
||||
|
||||
```javascript
|
||||
// assume App.start calls util.addListeners
|
||||
cy.spy(util, "addListeners")
|
||||
cy.spy(util, 'addListeners')
|
||||
App.start()
|
||||
expect(util.addListeners).to.be.called
|
||||
|
||||
```
|
||||
|
||||
## Example Recipe
|
||||
**Using cy.spy()**
|
||||
|
||||
{% note info Using cy.spy %}
|
||||
{% note info %}
|
||||
[Check out our example recipe testing spying, stubbing and time](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/spy_stub_clock_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
## Alias a spy
|
||||
|
||||
Adding an alias using [`cy.as`](https://on.cypress.io/api/as) to spies makes them easier to identify in error messages and Cypress's command log.
|
||||
Adding an alias using [`.as()`](https://on.cypress.io/api/as) to spies makes them easier to identify in error messages and Cypress' command log.
|
||||
|
||||
```javascript
|
||||
const obj = {
|
||||
foo () {}
|
||||
}
|
||||
const spy = cy.spy(obj, "foo").as("anyArgs")
|
||||
const withFoo = spy.withArgs("foo").as("withFoo")
|
||||
const spy = cy.spy(obj, 'foo').as('anyArgs')
|
||||
const withFoo = spy.withArgs('foo').as('withFoo')
|
||||
obj.foo()
|
||||
expect(spy).to.be.called
|
||||
expect(withFoo).to.be.called // purposefully failing assertion
|
||||
@@ -59,16 +78,30 @@ You will see the following in the command log:
|
||||
|
||||

|
||||
|
||||
# Notes
|
||||
|
||||
**Automatic reset/restore between tests**
|
||||
|
||||
`cy.spy` creates spies in a [sandbox](http://sinonjs.org/docs/#sandbox), so all spies created are automatically reset/restored between tests without you having to explicitly reset/restore them.
|
||||
|
||||
**Difference between cy.spy() and cy.stub()**
|
||||
|
||||
The main difference between `cy.spy` and [`cy.stub`](https://on.cypress.io/api/stub) is that `cy.spy` does not replace the method, it only wraps it. So, while invocations are recorded, the original method is still called. This can be very useful when testing methods on native browser objects. You can verify a method is being called by your test and still have the original method action invoked.
|
||||
|
||||
**Assertion Support**
|
||||
|
||||
Cypress has also built-in [sinon-chai](https://github.com/domenic/sinon-chai) support, so any [assertions](https://github.com/domenic/sinon-chai#assertions) supported by `sinon-chai` can be used without any configuration.
|
||||
|
||||
# Command Log
|
||||
|
||||
## Create a spy, alias it, and call it
|
||||
**Create a spy, alias it, and call it**
|
||||
|
||||
```javascript
|
||||
const obj = {
|
||||
foo () {}
|
||||
}
|
||||
const spy = cy.spy(obj, "foo").as("foo")
|
||||
obj.foo("foo", "bar")
|
||||
const spy = cy.spy(obj, 'foo').as('foo')
|
||||
obj.foo('foo', 'bar')
|
||||
expect(spy).to.be.called
|
||||
```
|
||||
|
||||
@@ -80,7 +113,7 @@ When clicking on the `spy-1` event within the command log, the console outputs t
|
||||
|
||||
<img width="585" alt="screen shot of console output" src="https://cloud.githubusercontent.com/assets/1157043/22437712/1d5ed1e6-e6f7-11e6-9808-e61936b1d75f.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [Guide: Stubs, Spies and Clocks ](https://on.cypress.io/guides/stubs-spies-clocks)
|
||||
- [Recipe: Controlling Behavior with Spies, Stubs, and Clocks](https://github.com/cypress-io/cypress-example-recipes#controlling-behavior-with-spies-stubs-and-clocks)
|
||||
|
||||
@@ -4,92 +4,118 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
A stub is used to replace a function, record its usage and control its behavior. You can track calls to the functions and what arguments the function was called with. You can also control what the function returns and even cause it to throw an exception.
|
||||
Replace a function, record its usage and control its behavior.
|
||||
|
||||
`cy.stub` returns a [sinon.js stub](http://sinonjs.org/docs/#stubs). All methods found on sinon.js spies and stubs are supported. `cy.stub` creates stubs in a [sandbox](http://sinonjs.org/docs/#sandbox), so all stubs created are automatically reset/restored between tests without you having to explicitly reset/restore them.
|
||||
# Syntax
|
||||
|
||||
Cypress has built-in [sinon-as-promised](https://github.com/bendrucker/sinon-as-promised) support, so the stubs returned by `cy.stub` supports the `.resolves` and `.rejects` API provided by `sinon-as-promised`.
|
||||
```javascript
|
||||
cy.stub()
|
||||
cy.stub(object, method)
|
||||
cy.stub(object, method, replacerFn)
|
||||
```
|
||||
|
||||
Cypress also has built-in [sinon-chai](https://github.com/domenic/sinon-chai) support, so any [assertions](https://github.com/domenic/sinon-chai#assertions) supported by `sinon-chai` can be used without any configuration.
|
||||
## Usage
|
||||
|
||||
`.stub()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.stub(user, 'addFriend')
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} object** ***(Object)***
|
||||
|
||||
The object that has the `method` to be replaced.
|
||||
|
||||
**{% fa fa-angle-right %} method** ***(String)***
|
||||
|
||||
The name of the `method` on the `object` to be wrapped.
|
||||
|
||||
**{% fa fa-angle-right %} replacerFn** ***(Function)***
|
||||
|
||||
The function used to replaces the `method` on the `object`.
|
||||
|
||||
|
||||
## Yields
|
||||
|
||||
Unlike most Cypress commands, `cy.stub` is *synchronous* and returns a value (the stub) instead of a Promise-like chain-able object.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the stub |
|
||||
`cy.stub` returns a [Sinon.js stub](http://sinonjs.org/docs/#stubs). All methods found on Sinon.JS [spies](http://sinonjs.org/docs/#spies-api) and [stubs](http://sinonjs.org/docs/#stubs-api) are supported.
|
||||
|
||||
# [cy.stub()](#usage)
|
||||
## Timeout
|
||||
|
||||
Creates and returns a stub. See the [sinon.js stub docs](http://sinonjs.org/docs/#stubs) for methods on the stub.
|
||||
# Examples
|
||||
|
||||
# [cy.stub( *object*, *"method"* )](#replace-a-method-with-a-stub)
|
||||
## Stub
|
||||
|
||||
Replaces the `method` on the `object` with a stub and returns the stub. See the [sinon.js stub docs](http://sinonjs.org/docs/#stubs) for methods on the stub.
|
||||
|
||||
# [cy.stub( *object*, *"method"*, replacerFn )](#replace-a-method-with-a-function)
|
||||
|
||||
Replaces the `method` on the `object` with the `replacerFn` wrapped in a spy.See the [sinon.js spy docs](http://sinonjs.org/docs/#spies) for methods on the spy.
|
||||
|
||||
# Usage
|
||||
|
||||
## Create a stub and manually replace a function
|
||||
**Create a stub and manually replace a function**
|
||||
|
||||
```javascript
|
||||
// assume App.start calls util.addListeners
|
||||
util.addListeners = cy.stub()
|
||||
|
||||
App.start()
|
||||
expect(util.addListeners).to.be.called
|
||||
```
|
||||
|
||||
## Replace a method with a stub
|
||||
**Replace a method with a stub**
|
||||
|
||||
```javascript
|
||||
// assume App.start calls util.addListeners
|
||||
cy.stub(util, "addListeners")
|
||||
cy.stub(util, 'addListeners')
|
||||
|
||||
App.start()
|
||||
expect(util.addListeners).to.be.called
|
||||
```
|
||||
|
||||
## Replace a method with a function
|
||||
**Replace a method with a function**
|
||||
|
||||
```javascript
|
||||
// assume App.start calls util.addListeners
|
||||
let listenersAdded = false
|
||||
cy.stub(util, "addListeners", function () {
|
||||
|
||||
cy.stub(util, 'addListeners', function () {
|
||||
listenersAdded = true
|
||||
})
|
||||
|
||||
App.start()
|
||||
expect(listenersAdded).to.be.true
|
||||
```
|
||||
|
||||
## Specify the return value of a stubbed method
|
||||
**Specify the return value of a stubbed method**
|
||||
|
||||
```javascript
|
||||
// assume App.start calls util.addListeners, which returns a function
|
||||
// that removes the listeners
|
||||
const removeStub = cy.stub()
|
||||
cy.stub(util, "addListeners").returns(removeStub)
|
||||
|
||||
cy.stub(util, 'addListeners').returns(removeStub)
|
||||
|
||||
App.start()
|
||||
App.stop()
|
||||
expect(removeStub).to.be.called
|
||||
```
|
||||
|
||||
## Example Recipe
|
||||
**Using cy.stub**
|
||||
|
||||
{% note info Using cy.stub %}
|
||||
{% note info %}
|
||||
[Check out our example recipe testing spying, stubbing and time](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/spy_stub_clock_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
## Alias a stub
|
||||
|
||||
Adding an alias using [`cy.as`](https://on.cypress.io/api/as) to stubs makes them easier to identify in error messages and Cypress's command log.
|
||||
Adding an alias using [`.as()`](https://on.cypress.io/api/as) to stubs makes them easier to identify in error messages and Cypress' command log.
|
||||
|
||||
```javascript
|
||||
const obj = {
|
||||
foo () {}
|
||||
}
|
||||
const stub = cy.stub(obj, "foo").as("anyArgs")
|
||||
const withFoo = stub.withArgs("foo").as("withFoo")
|
||||
const stub = cy.stub(obj, 'foo').as('anyArgs')
|
||||
const withFoo = stub.withArgs('foo').as('withFoo')
|
||||
|
||||
obj.foo()
|
||||
expect(stub).to.be.called
|
||||
expect(withFoo).to.be.called // purposefully failing assertion
|
||||
@@ -99,16 +125,30 @@ You will see the following in the command log:
|
||||
|
||||

|
||||
|
||||
# Notes
|
||||
|
||||
**Automatic reset/restore between tests**
|
||||
|
||||
`cy.stub` creates stubs in a [sandbox](http://sinonjs.org/docs/#sandbox), so all stubs created are automatically reset/restored between tests without you having to explicitly reset/restore them.
|
||||
|
||||
**Difference between cy.spy() and cy.stub()**
|
||||
|
||||
The main difference between `cy.spy` and [`cy.stub`](https://on.cypress.io/api/stub) is that `cy.spy` does not replace the method, it only wraps it. So, while invocations are recorded, the original method is still called. This can be very useful when testing methods on native browser objects. You can verify a method is being called by your test and still have the original method action invoked.
|
||||
|
||||
**Assertion Support**
|
||||
|
||||
Cypress has built-in [sinon-as-promised](https://github.com/bendrucker/sinon-as-promised) support, so the stubs returned by `cy.stub` supports the `.resolves` and `.rejects` API provided by `sinon-as-promised`.
|
||||
|
||||
# Command Log
|
||||
|
||||
## Create a stub, alias it, and call it
|
||||
**Create a stub, alias it, and call it**
|
||||
|
||||
```javascript
|
||||
const obj = {
|
||||
foo () {}
|
||||
}
|
||||
const stub = cy.stub(obj, "foo").as("foo")
|
||||
obj.foo("foo", "bar")
|
||||
const stub = cy.stub(obj, 'foo').as('foo')
|
||||
obj.foo('foo', 'bar')
|
||||
expect(stub).to.be.called
|
||||
```
|
||||
|
||||
@@ -120,7 +160,7 @@ When clicking on the `(stub-1)` event within the command log, the console output
|
||||
|
||||
<img width="585" alt="screen shot of console output" src="https://cloud.githubusercontent.com/assets/1157043/22437546/6b01e574-e6f6-11e6-878f-e10c2316d213.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [Guide: Stubs, Spies and Clocks ](https://on.cypress.io/guides/stubs-spies-clocks)
|
||||
- [Recipe: Controlling Behavior with Spies, Stubs, and Clocks](https://github.com/cypress-io/cypress-example-recipes#controlling-behavior-with-spies-stubs-and-clocks)
|
||||
|
||||
@@ -4,33 +4,52 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Submits the DOM element from the previous command if it is a form. Submit can only be called on a single form.
|
||||
|
||||
**The following events are fired during submit:** `submit`
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.submit` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts). |
|
||||
|
||||
# [cy.submit()](#usage)
|
||||
|
||||
Submit a form.
|
||||
|
||||
# Options
|
||||
# Syntax
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.submit`.
|
||||
```javascript
|
||||
.submit()
|
||||
.submit(options)
|
||||
```
|
||||
|
||||
**cy.submit( *options* )**
|
||||
## Usage
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
`.submit()` requires being chained off another cy command that *yields* a form.
|
||||
|
||||
# Usage
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.get('form').submit() // Submit a form
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.submit() // Errors, cannot be chained off 'cy'
|
||||
cy.get('input').submit() // Errors, 'input' does not yield a form
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.submit()`.
|
||||
|
||||
## Yields
|
||||
|
||||
`.submit()` yields the form that was submitted.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.submit()` will continue to try to submit the form for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Example
|
||||
|
||||
## Submit a form
|
||||
|
||||
**Submit can only be called on a single form.**
|
||||
|
||||
```html
|
||||
<form id="contact">
|
||||
<input type="text" name="message">
|
||||
@@ -39,18 +58,16 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
// submits the form and performs all default actions
|
||||
// returns <form> for further chaining
|
||||
cy.get("#contact").submit()
|
||||
cy.get('#contact').submit()
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Submit a form
|
||||
**Submit a form**
|
||||
|
||||
```javascript
|
||||
cy.route("POST", /users/, "fixture:user").as("userSuccess")
|
||||
cy.get("form").submit()
|
||||
cy.route('POST', '/users', 'fixture:user').as('userSuccess')
|
||||
cy.get('form').submit()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -61,6 +78,6 @@ When clicking on `submit` within the command log, the console outputs the follow
|
||||
|
||||

|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [click](https://on.cypress.io/api/click)
|
||||
|
||||
@@ -4,26 +4,57 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
`cy.then()` will yield you the current subject as the first argument.
|
||||
Yield the current yielded subject as the first argument of a function.
|
||||
|
||||
`cy.then()` is modeled identically to the way Promises work in JavaScript. Whatever is returned from the callback function becomes the new subject, and will flow into the next command, with the exception of `null` and `undefined`.
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
.spread(callbackFn)
|
||||
.spread(options, callbackFn)
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`.then()` should be chained off another cy command.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.get('.nav').then(function(nav) {}) // Yields .nav as first arg
|
||||
cy.location().then(function(loc) {}) // Yields location object as first arg
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} callbackFn** ***(Function)***
|
||||
|
||||
Pass a function that takes the current yielded subject as it's first argument.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.then()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to yield the then
|
||||
|
||||
## Yields
|
||||
|
||||
`.then()` is modeled identically to the way Promises work in JavaScript. Whatever is returned from the callback function becomes the new subject and will flow into the next command (with the exception of `null` and `undefined`).
|
||||
|
||||
When `null` or `undefined` is returned by the callback function, the subject will not be modified and will instead carry over to the next command.
|
||||
|
||||
Just like Promises, you can return any compatible "thenable" (anything that has a `.then()` interface) and Cypress will wait for that to resolve before continuing forward through the chain of commands.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the return of the callback function |
|
||||
| **Timeout** | `cy.then` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's [options](#options). |
|
||||
## Timeout
|
||||
|
||||
# [cy.then( *function* )](#usage)
|
||||
`.then` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's [options](#options).
|
||||
|
||||
Yield the current subject as the first argument.
|
||||
# Examples
|
||||
|
||||
# Usage
|
||||
## Work with DOM element
|
||||
|
||||
## The element `input` is yielded
|
||||
**The element `input` is yielded**
|
||||
|
||||
```html
|
||||
<form id="todos">
|
||||
@@ -32,66 +63,48 @@ Yield the current subject as the first argument.
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy.get("form").find("input").then(function($input){
|
||||
// work with $input subject here
|
||||
// we can potentially use it within an assertion
|
||||
// or just call some methods on it and return a new subject
|
||||
cy.get('form').find('input').then(function($input){
|
||||
// work with $input here
|
||||
})
|
||||
```
|
||||
|
||||
# Options
|
||||
## Change subject
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.then`.
|
||||
|
||||
**[cy.click( *options*, *function* )](#options-usage)**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the click
|
||||
|
||||
# Usage
|
||||
|
||||
## Assert explicitly about the subject `<li>`'s
|
||||
|
||||
```html
|
||||
<div id="todos">
|
||||
<li>Walk the dog</li>
|
||||
<li>Feed the cat</li>
|
||||
<li>Write JavaScript</li>
|
||||
</div>
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy.get("#todos li").then(function($lis){
|
||||
expect($lis).to.have.length(3)
|
||||
expect($lis.eq(0)).to.contain("Walk the dog")
|
||||
expect($lis.eq(1)).to.contain("Feed the cat")
|
||||
expect($lis.eq(2)).to.contain("Write JavaScript")
|
||||
})
|
||||
```
|
||||
|
||||
Normally you'd use implicit subject assertions via [should](https://on.cypress.io/api/should) or [and](https://on.cypress.io/api/and), but it's sometimes it's more convenient to write explicit assertions about a given subject.
|
||||
|
||||
{% note warning %}
|
||||
Any errors raised by failed assertions will immediately bubble up and cause the test to fail.
|
||||
{% endnote %}
|
||||
|
||||
## The subject is changed by returning `{foo: 'bar'}`
|
||||
**The subject is changed by returning `{foo: 'bar'}`**
|
||||
|
||||
```javascript
|
||||
cy.then(function(){
|
||||
return {foo: "bar"}
|
||||
return {foo: 'bar'}
|
||||
}).then(function(obj){
|
||||
// subject is now the obj {foo: "bar"}
|
||||
expect(obj).to.deep.eq({foo: "bar"}) // true
|
||||
// subject is now the obj {foo: 'bar'}
|
||||
expect(obj).to.deep.eq({foo: 'bar'}) // true
|
||||
})
|
||||
```
|
||||
|
||||
## Cypress waits for the Promise to resolve before continuing
|
||||
**Returning `null` or `undefined` will not modify the subject**
|
||||
|
||||
```javascript
|
||||
// if using Q
|
||||
cy.get("button").click().then(function($button){
|
||||
cy
|
||||
.get('form').then(function($form){
|
||||
console.log('form is:', $form)
|
||||
// undefined is returned here, therefore
|
||||
// the $form subject will automatically
|
||||
// carry over and allow for continued chaining
|
||||
}).find('input').then(function($input){
|
||||
// we have our real $input element here since
|
||||
// our form element carried over and we called
|
||||
// .find("input") on it
|
||||
})
|
||||
```
|
||||
|
||||
## Promises
|
||||
|
||||
**Cypress waits for the Promise to resolve before continuing**
|
||||
|
||||
***Example using Q***
|
||||
|
||||
```javascript
|
||||
cy.get('button').click().then(function($button){
|
||||
var p = Q.defer()
|
||||
|
||||
setTimeout(function(){
|
||||
@@ -100,14 +113,20 @@ cy.get("button").click().then(function($button){
|
||||
|
||||
return p.promise
|
||||
})
|
||||
```
|
||||
|
||||
// if using bluebird
|
||||
cy.get("button").click().then(function($button){
|
||||
***Example using bluebird***
|
||||
|
||||
```javascript
|
||||
cy.get('button').click().then(function($button){
|
||||
return Promise.delay(5000)
|
||||
})
|
||||
```
|
||||
|
||||
// if using jQuery deferred's
|
||||
cy.get("button").click().then(function($button){
|
||||
***Example using jQuery deferred's***
|
||||
|
||||
```javascript
|
||||
cy.get('button').click().then(function($button){
|
||||
var df = $.Deferred()
|
||||
|
||||
setTimeout(function(){
|
||||
@@ -118,32 +137,11 @@ cy.get("button").click().then(function($button){
|
||||
})
|
||||
```
|
||||
|
||||
## Returning `null` or `undefined` will not modify the subject
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("form").then(function($form){
|
||||
console.log("form is:", $form)
|
||||
// undefined is returned here, therefore
|
||||
// the $form subject will automatically
|
||||
// carry over and allow for continued chaining
|
||||
}).find("input").then(function($input){
|
||||
// we have our real $input element here since
|
||||
// our form element carried over and we called
|
||||
// .find("input") on it
|
||||
})
|
||||
```
|
||||
|
||||
# Options Usage
|
||||
|
||||
```javascript
|
||||
cy.then({timeout: 7000}, function(){
|
||||
// code here
|
||||
})
|
||||
```
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [and](https://on.cypress.io/api/and)
|
||||
- [its](https://on.cypress.io/api/its)
|
||||
- [invoke](https://on.cypress.io/api/invoke)
|
||||
- [should](https://on.cypress.io/api/should)
|
||||
- [spread](https://on.cypress.io/api/spread)
|
||||
- [Issuing Commands](https://on.cypress.io/guides/issuing-commands)
|
||||
|
||||
@@ -4,56 +4,85 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
`cy.tick` is used to move time after overriding native time functions with [`cy.clock`](https://on.cypress.io/api/clock).
|
||||
|
||||
It moves the clock the specified number of `milliseconds`. Any timers within the affected range of time will be called.
|
||||
Move time after overriding a native time function with [`cy.clock()`](https://on.cypress.io/api/clock).
|
||||
|
||||
{% note warning %}
|
||||
[`cy.clock`](https://on.cypress.io/api/clock) must be called before `cy.tick` in order to override native time functions first.
|
||||
{% endnote %}
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the `clock` object. See [clock API](https://on.cypress.io/api/clock#clock-api) |
|
||||
# Syntax
|
||||
|
||||
# [cy.tick( *milliseconds* )](#usage)
|
||||
```javascript
|
||||
cy.tick(milliseconds)
|
||||
```
|
||||
|
||||
Moves the clock the specified number of `milliseconds`. Any timers within the affected range of time will be called.
|
||||
## Usage
|
||||
|
||||
# Usage
|
||||
`cy.tick()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
## Create a clock and move time to trigger a setTimeout
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.tick(500)
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} milliseconds** ***(Number)***
|
||||
|
||||
The number of `milliseconds` to move the clock. Any timers within the affected range of time will be called.
|
||||
|
||||
## Yields
|
||||
|
||||
`.tick()` yields a `clock` object with the following methods:
|
||||
|
||||
**`clock.tick(milliseconds)`**
|
||||
|
||||
Move the clock a number of milliseconds. Any timers within the affected range of time will be called.
|
||||
|
||||
**`clock.restore()`**
|
||||
|
||||
Restore all overridden native functions. This is automatically called between tests, so should not generally be needed.
|
||||
|
||||
You can also access the `clock` object via `this.clock` in a [`.then()`](https://on.cypress.io/api/then) callback.
|
||||
|
||||
|
||||
# Examples
|
||||
|
||||
## Move time
|
||||
|
||||
**Create a clock and move time to trigger a `setTimeout`**
|
||||
|
||||
```javascript
|
||||
// app code loaded by index.html
|
||||
window.foo = () => {
|
||||
window.addIntro = () => {
|
||||
setTimeout(() => {
|
||||
document.getElementById('#foo').textContent = 'Foo'
|
||||
document.getElementById('#header').textContent = 'Hello, World'
|
||||
}, 500)
|
||||
}
|
||||
|
||||
// test
|
||||
cy
|
||||
.clock()
|
||||
.visit("/index.html")
|
||||
.window().invoke("foo")
|
||||
.tick(500)
|
||||
.get("#foo")
|
||||
.should("have.text", "Foo")
|
||||
```
|
||||
|
||||
## Example Recipe
|
||||
```javascript
|
||||
cy.clock()
|
||||
cy.visit('/index.html')
|
||||
cy.window().invoke('addIntro')
|
||||
cy.tick(500)
|
||||
cy.get('#header').should('have.text', 'Hello, World')
|
||||
```
|
||||
|
||||
{% note info Using cy.clock and cy.tick %}
|
||||
**Using cy.clock and cy.tick**
|
||||
|
||||
{% note info %}
|
||||
[Check out our example recipe testing spying, stubbing and time](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/spy_stub_clock_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
# Command Log
|
||||
|
||||
## Create a clock and tick it 1 second
|
||||
**Create a clock and tick it 1 second**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.clock()
|
||||
.tick(1000)
|
||||
cy.clock()
|
||||
cy.tick(1000)
|
||||
```
|
||||
|
||||
The command above will display in the command log as:
|
||||
@@ -64,10 +93,10 @@ When clicking on the `tick` command within the command log, the console outputs
|
||||
|
||||
<img width="1059" alt="screen shot of console output" src="https://cloud.githubusercontent.com/assets/1157043/22438009/504fecd8-e6f8-11e6-8ef1-4d7cb0b5594c.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [clock](https://on.cypress.io/api/clock)
|
||||
- [Guide: Stubs, Spies and Clocks ](https://on.cypress.io/guides/stubs-spies-clocks)
|
||||
- [Recipe: Controlling Behavior with Spies, Stubs, and Clocks](https://github.com/cypress-io/cypress-example-recipes#controlling-behavior-with-spies-stubs-and-clocks)
|
||||
- [clock](https://on.cypress.io/api/clock)
|
||||
- [stub](https://on.cypress.io/api/stub)
|
||||
- [spy](https://on.cypress.io/api/spy)
|
||||
- [stub](https://on.cypress.io/api/stub)
|
||||
|
||||
@@ -6,39 +6,59 @@ description: ''
|
||||
|
||||
Get the title of the document.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the `document` title as a string |
|
||||
| **Timeout** | `cy.title` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
|
||||
# [cy.title()](#usage)
|
||||
# Syntax
|
||||
|
||||
Get the title of the document.
|
||||
```javascript
|
||||
cy.title()
|
||||
cy.title(options)
|
||||
```
|
||||
|
||||
# Options
|
||||
## Usage
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.click`.
|
||||
`cy.title()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**cy.title( *options* )**
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.title()
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.title`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
|
||||
## Assert that the document's title contains "New User"
|
||||
## Yields
|
||||
|
||||
`cy.title()` yields the `document` title as a string.
|
||||
|
||||
## Timeout
|
||||
|
||||
`cy.title()` will continue to retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Title
|
||||
|
||||
**Assert that the document's title eq "My Awesome Application"**
|
||||
|
||||
```javascript
|
||||
cy.title().should("contain", "New User")
|
||||
cy.title().should('eq', 'My Awesome Application')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Assert that the document's title contains "New User"
|
||||
**Assert that the document's title include 'New User'**
|
||||
|
||||
```javascript
|
||||
cy.title().should("contain", "New User")
|
||||
cy.title().should('include', 'New User')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -49,6 +69,6 @@ When clicking on `title` within the command log, the console outputs the followi
|
||||
|
||||
<img width="437" alt="screen shot 2015-11-29 at 2 13 06 pm" src="https://cloud.githubusercontent.com/assets/1271364/11459377/5b8110e2-96a3-11e5-97e6-fbeb80f83277.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [document](https://on.cypress.io/api/document)
|
||||
|
||||
@@ -4,112 +4,166 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
`cy.trigger` is used to trigger an arbitrary event (e.g. mouseover, contextmenu) on the DOM element found in the previous command. The DOM element must be in an "interactable" state prior to the triggered event happening (it must be visible and not disabled).
|
||||
Trigger an event on a DOM element.
|
||||
|
||||
`cy.trigger` is meant to be a low-level utility that makes triggering events easier than manually constructing and dispatching them. Since any arbitrary event can be triggered, Cypress tries not to make any assumptions about how it should be triggered. This means you'll need to know the implementation details (which may be in a 3rd party library) of the event handler(s) receiving the event and provide the necessary properties.
|
||||
# Syntax
|
||||
|
||||
Cypress automatically scrolls the element into view prior to attempting to trigger the event.
|
||||
```javascript
|
||||
.trigger(eventName)
|
||||
.trigger(eventName, position)
|
||||
.trigger(eventName, options)
|
||||
.trigger(eventName, x, y)
|
||||
.trigger(eventName, position, options)
|
||||
.trigger(eventName, x, y, options)
|
||||
```
|
||||
|
||||
By default, the event is triggered with coordinates at the exact center of the element. You can pass a [`position`](#position-usage) option, relative coordinates, or the raw event properties (e.g. `clientX`) to override this.
|
||||
## Usage
|
||||
|
||||
By default, the event will bubble and is cancelable. You can pass `bubbles: false` and/or `cancelable: false` as options to override this.
|
||||
`.trigger()` requires being chained off another cy command that *yields* a DOM element.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the existing DOM subject |
|
||||
| **Timeout** | `cy.trigger` will wait and retry until the element is 'interactable' for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's [options](#options) |
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# [cy.trigger( *eventName* )](#usage)
|
||||
```javascript
|
||||
cy.get('a').trigger('mousedown') // Trigger mousedown event on link
|
||||
```
|
||||
|
||||
Trigger the event named `eventName` on the DOM element.
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
# [cy.trigger( *eventName*, *position* )](#position-usage)
|
||||
```javascript
|
||||
cy.trigger('touchstart') // Errors, cannot be chained off 'cy'
|
||||
cy.location().trigger('mouseleave') // Errors, 'location' does not yield DOM element
|
||||
```
|
||||
|
||||
Triggers event on the element at the specified position. The `center` position is the default position.
|
||||
## Arguments
|
||||
|
||||
Position | Default | Notes
|
||||
--- | --- | ---
|
||||
`center` | Yes | The exact center of the element
|
||||
`topLeft` | No | The top left corner of the element
|
||||
`topRight` | No | The top right corner of the element
|
||||
`bottomLeft` | No | The bottom left corner of the element
|
||||
`bottomRight` | No | The bottom right corner of the element
|
||||
**{% fa fa-angle-right %} eventName** ***(String)***
|
||||
|
||||
# [cy.trigger( *eventName*, *x*, *y* )](#coordinates-usage)
|
||||
The name of the `event` to be triggered on the DOM element.
|
||||
|
||||
You can pass a relative `x` and `y` coordinate which will calculate distance in pixels from the top left corner of the element and triggers the event with the calculated coordinates.
|
||||
|
||||
`x` and `y` must both be `Numbers`. Currently you cannot use `%` based arguments. [Open an issue](https://github.com/cypress-io/cypress/issues/new?body=**Description**%0A*Include%20a%20high%20level%20description%20of%20the%20error%20here%20including%20steps%20of%20how%20to%20recreate.%20Include%20any%20benefits%2C%20challenges%20or%20considerations.*%0A%0A**Code**%0A*Include%20the%20commands%20used*%0A%0A**Steps%20To%20Reproduce**%0A-%20%5B%20%5D%20Steps%0A-%20%5B%20%5D%20To%0A-%20%5B%20%5D%20Reproduce%2FFix%0A%0A**Additional%20Info**%0A*Include%20any%20images%2C%20notes%2C%20or%20whatever.*%0A) if you'd like this functionality.
|
||||
**{% fa fa-angle-right %} position** ***(String)***
|
||||
|
||||
# Options
|
||||
The position where the event should be triggered. The `center` position is the default position. Valid positions are `topLeft`, `top`, `topRight`, `left`, `center`, `right`, `bottomLeft`, `bottom`, and `bottomRight`.
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.click`.
|
||||

|
||||
|
||||
**[cy.trigger( *eventName*, *options* )](#options-usage)**
|
||||
**[cy.trigger( *eventName*, *position*, *options* )](#options-usage)**
|
||||
**[cy.trigger( *eventName*, *x*, *y*, *options* )](#options-usage)**
|
||||
**{% fa fa-angle-right %} x** ***(Number)***
|
||||
|
||||
The distance in pixels from element's left to trigger the event.
|
||||
|
||||
**{% fa fa-angle-right %} y** ***(Number)***
|
||||
|
||||
The distance in pixels from element's top to trigger the event.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.trigger()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`bubbles` | `true` | Whether the event bubbles
|
||||
`cancelable` | `true` | Whether the event is cancelable
|
||||
`interval` | `16` | Interval which to retry triggering the event
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the click
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry triggering the event
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
You can also include arbitrary event properties (e.g. `clientX`, `shiftKey`) and they will be attached to the event. Passing in coordinate arguments (`clientX`, `pageX`, etc) will override the position coordinates.
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Trigger a mouseover on the button
|
||||
`.trigger()` yields the DOM subject chained from the previous command.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.trigger()` will wait until the element is in an 'interactable' state for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's options
|
||||
|
||||
|
||||
The DOM element must be in an "interactable" state prior to the triggered event happening (it must be visible and not disabled).
|
||||
|
||||
|
||||
|
||||
Cypress automatically scrolls the element into view prior to attempting to trigger the event.
|
||||
|
||||
# Examples
|
||||
|
||||
## Mouse Events
|
||||
|
||||
**Trigger a `mouseover` on the button**
|
||||
|
||||
```javascript
|
||||
// returns <button>Save</button>
|
||||
cy.get("button").trigger("mouseover")
|
||||
cy.get('button').trigger('mouseover') // yields 'button'
|
||||
```
|
||||
|
||||
# Position Usage
|
||||
**Drag and Drop**
|
||||
|
||||
## Trigger a mousedown on the top right of a button
|
||||
{% note info %}
|
||||
[Check out our example recipe triggering mouse and drag events to test dragging and dropping](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/drag_n_drop_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
## Change Event
|
||||
|
||||
**Interact with a range input (slider**)
|
||||
|
||||
To interact with a range input (slider), we need to set its value and
|
||||
then trigger the appropriate event to signal it has changed.
|
||||
|
||||
Below we invoke jQuery's `val()` method to set the value, then trigger the `change` event.
|
||||
|
||||
Note that some implementations may rely on the `input` event instead, which is fired as a user moves the slider, but is not supported by some browsers.
|
||||
|
||||
```javascript
|
||||
// mousedown is issued in the top right corner of the element
|
||||
cy.get("button").trigger("mousedown", "topRight")
|
||||
cy.get('input[type=range]').as('range')
|
||||
.invoke('val', 25)
|
||||
.ttrigger('change')
|
||||
cy.get('@range').siblings('p').should('have.text', '25')
|
||||
```
|
||||
|
||||
# Coordinates Usage
|
||||
## Position
|
||||
|
||||
## Specify explicit coordinates relative to the top left corner
|
||||
**Trigger a `mousedown` on the top right of a button**
|
||||
|
||||
```javascript
|
||||
// the contextmenu event will be issued inside of the element
|
||||
// 15px from the left and
|
||||
// 40px from the top
|
||||
cy.get("button").trigger("contextmenu", 15, 40)
|
||||
cy.get('button').trigger('mousedown', 'topRight')
|
||||
```
|
||||
|
||||
# Options Usage
|
||||
## Coordinates
|
||||
|
||||
## Specify that the event should not bubble
|
||||
**Specify explicit coordinates relative to the top left corner**
|
||||
|
||||
```javascript
|
||||
cy.get('button').trigger('contextmenu', 15, 40)
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
**Specify that the event should not bubble**
|
||||
|
||||
By default, the event will bubble up the DOM tree. This will prevent the event from bubbling.
|
||||
|
||||
```javascript
|
||||
cy.get("button").trigger("mouseover", {bubbles: false})
|
||||
cy.get('button').trigger('mouseover', { bubbles: false })
|
||||
```
|
||||
|
||||
## Specify the exact clientX and clientY the event should have
|
||||
**Specify the exact `clientX` and `clientY` the event should have**
|
||||
|
||||
This overrides the default auto-positioning based on the element itself. Useful for events like `mousemove` where you need the position to be outside the element itself.
|
||||
|
||||
```javascript
|
||||
cy.get("button").trigger("mousemove", {clientX: 200, clientY: 300})
|
||||
cy.get('button').trigger('mousemove', {clientX: 200, clientY: 300})
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
**What event should I fire?**
|
||||
|
||||
`cy.trigger` is meant to be a low-level utility that makes triggering events easier than manually constructing and dispatching them. Since any arbitrary event can be triggered, Cypress tries not to make any assumptions about how it should be triggered. This means you'll need to know the implementation details (which may be in a 3rd party library) of the event handler(s) receiving the event and provide the necessary properties.
|
||||
|
||||
# Command Log
|
||||
|
||||
## Trigger a mouseover event on the first button
|
||||
**Trigger a `mouseover` event on the first button**
|
||||
|
||||
```javascript
|
||||
cy.get("button").first().trigger("mouseover")
|
||||
cy.get('button').first().trigger('mouseover')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -120,13 +174,13 @@ When clicking on `trigger` within the command log, the console outputs the follo
|
||||
|
||||
<img width="630" alt="Console output" src="https://cloud.githubusercontent.com/assets/1157043/23477276/749aac54-fe8b-11e6-81b3-e7600cca0ba0.png">
|
||||
|
||||
# Errors
|
||||
# See also
|
||||
|
||||
## cy.trigger() can only be called on a single element.
|
||||
|
||||
`cy.trigger()` only works on a single element. [Open an issue](https://github.com/cypress-io/cypress/issues/new?body=**Description**%0A*Include%20a%20high%20level%20description%20of%20the%20error%20here%20including%20steps%20of%20how%20to%20recreate.%20Include%20any%20benefits%2C%20challenges%20or%20considerations.*%0A%0A**Code**%0A*Include%20the%20commands%20used*%0A%0A**Steps%20To%20Reproduce**%0A-%20%5B%20%5D%20Steps%0A-%20%5B%20%5D%20To%0A-%20%5B%20%5D%20Reproduce%2FFix%0A%0A**Additional%20Info**%0A*Include%20any%20images%2C%20notes%2C%20or%20whatever.*%0A) if you'd like to be able to trigger an event serially on multiple elements.
|
||||
|
||||
# Related
|
||||
|
||||
- [hover](https://on.cypress.io/api/hover)
|
||||
- [blur](https://on.cypress.io/api/blur)
|
||||
- [check](https://on.cypress.io/api/check)
|
||||
- [click](https://on.cypress.io/api/click)
|
||||
- [focus](https://on.cypress.io/api/focus)
|
||||
- [select](https://on.cypress.io/api/select)
|
||||
- [submit](https://on.cypress.io/api/submit)
|
||||
- [type](https://on.cypress.io/api/type)
|
||||
- [uncheck](https://on.cypress.io/api/uncheck)
|
||||
|
||||
@@ -4,11 +4,40 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Types into the DOM element found in the previous command.
|
||||
Type into a DOM element.
|
||||
|
||||
Prior to typing, if the DOM element isn't currently focused, Cypress will issue a [click](https://on.cypress.io/api/click) on the element, which will cause the element to receive focus.
|
||||
|
||||
Text passed to `cy.type` may include any of these special character sequences:
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
.type(text)
|
||||
.type(text, options)
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`.type()` requires being chained off another cy command that *yields* a DOM element.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.get('input').type('Hello, World') // Type 'Hello, World' into the 'input'
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.type('Welcome') // Errors, cannot be chained off 'cy'
|
||||
cy.url().type('www.cypress.io') // Errors, 'url' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} text** ***(String)***
|
||||
|
||||
The text to be typed into the DOM element.
|
||||
|
||||
Text passed to `.type()` may include any of these special character sequences:
|
||||
|
||||
Sequence | Notes
|
||||
--- | ---
|
||||
@@ -32,20 +61,9 @@ Sequence | Notes
|
||||
`{meta}` | Activates the `metaKey` modifier. Aliases: `{command}`, `{cmd}`
|
||||
`{shift}` | Activates the `shiftKey` modifier.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the DOM element that was typed into |
|
||||
| **Timeout** | `cy.type` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's [options](#options). |
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
# [cy.type( *text* )](#usage)
|
||||
|
||||
Types the text provided into the current DOM subject.
|
||||
|
||||
# Options
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.type`.
|
||||
|
||||
**[cy.type( *text*, *options* )](#options-usage)**
|
||||
Pass in an options object to change the default behavior of `.type()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
@@ -53,105 +71,166 @@ Option | Default | Notes
|
||||
`force` | `false` | Forces type, disables error checking prior to type
|
||||
`release` | `true` | Keep a modifier activated between commands
|
||||
`interval` | `16` | Interval to retry type
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the type
|
||||
`log` | `true` | whether to display command in command log
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the type
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Type into a textarea.
|
||||
`.type()` yields the DOM element that was typed into.
|
||||
|
||||
## Timeout
|
||||
|
||||
`.type()` will continue to retry typing for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Input/Textarea
|
||||
|
||||
**Type into a textarea.**
|
||||
|
||||
```javascript
|
||||
// issues all keyboard events
|
||||
// and returns <textarea> for further chaining
|
||||
cy.get("textarea").type("Hello world")
|
||||
cy.get('textarea').type('Hello world') //yields <textarea>
|
||||
```
|
||||
|
||||
## Type into a non-text or non-textarea element with `tabindex`
|
||||
**Type into a login form**
|
||||
|
||||
{% note info %}
|
||||
[Check out our example recipe of logging in by typing username and password](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_html_web_form_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
**Mimic user typing behavior**
|
||||
|
||||
```javascript
|
||||
// each keypress is delayed 10ms by default
|
||||
// which simulates how a very fast user types!
|
||||
cy.get('[contenteditable]').type('some text!')
|
||||
```
|
||||
|
||||
## Not Input/Textarea
|
||||
|
||||
**Type into a non-input or non-textarea element with `tabindex`**
|
||||
|
||||
```html
|
||||
<body>
|
||||
<div id="el" tabindex="1">
|
||||
this div can receive focus
|
||||
This div can receive focus!
|
||||
</div>
|
||||
</body>
|
||||
```
|
||||
|
||||
```javascript
|
||||
// this element will receive all of the appropriate
|
||||
// key events and focus / blur events but will not
|
||||
// have its value or text contents altered in any way
|
||||
cy.get("#el").type("foo")
|
||||
cy.get('#el').type('supercalifragilisticexpialidocious')
|
||||
```
|
||||
|
||||
# Options Usage
|
||||
## Date Inputs
|
||||
|
||||
## Force a click to happen prior to type
|
||||
Using `.type()` on a date input (`<input type="date">`) requires specifying a valid date in the format:
|
||||
|
||||
Type issues a [`click`](https://on.cypress.io/api/click) prior to typing (only if the element is not currently focused). Because of this, sometimes it is useful to force the click to happen. Forcing a click disables error checking prior to the click.
|
||||
- `yyyy-MM-dd` (e.g. `1999-12-31`)
|
||||
|
||||
This isn't exactly how a user would type into a date input, but is a workaround since date input support varies between browsers and the format varies based on locale. `yyyy-MM-dd` is the format required by [the W3 spec](https://www.w3.org/TR/html/infrastructure.html#sec-dates) and is what the input's `value` will be set to regardless of browser or locale.
|
||||
|
||||
Special characters (`{leftarrow}`, `{selectall}`, etc) are not permitted.
|
||||
|
||||
## Month Inputs
|
||||
|
||||
Using `.type()` on a month input (`<input type="month">`) requires specifying a valid month in the format:
|
||||
|
||||
- `yyyy-MM` (e.g. `1999-12`)
|
||||
|
||||
This isn't exactly how a user would type into a month input, but is a workaround since month input support varies between browsers and the format varies based on locale. `yyyy-MM` is the format required by [the W3 spec](https://www.w3.org/TR/html/infrastructure.html#months) and is what the input's `value` will be set to regardless of browser or locale.
|
||||
|
||||
Special characters (`{leftarrow}`, `{selectall}`, etc) are not permitted.
|
||||
|
||||
## Week Inputs
|
||||
|
||||
Using `.type()` on a week input (`<input type="week">`) requires specifying a valid week in the format:
|
||||
|
||||
- `yyyy-Www` (e.g. `1999-W23`)
|
||||
|
||||
Where `W` is the literal character 'W' and `ww` is the number of the week (01-53).
|
||||
|
||||
This isn't exactly how a user would type into a week input, but is a workaround since week input support varies between browsers and the format varies based on locale. `yyyy-Www` is the format required by [the W3 spec](https://www.w3.org/TR/html/infrastructure.html#valid-week-string) and is what the input's `value` will be set to regardless of browser or locale.
|
||||
|
||||
Special characters (`{leftarrow}`, `{selectall}`, etc) are not permitted.
|
||||
|
||||
## Time Inputs
|
||||
|
||||
Using `.type()` on a time input (`<input type="time">`) requires specifying a valid time in the format:
|
||||
|
||||
- `HH:mm` (e.g. `01:30` or `23:15`)
|
||||
- `HH:mm:ss` (e.g. `10:00:30`)
|
||||
- `HH:mm:ss.SSS` (e.g. `12:00:00.384`)
|
||||
|
||||
Where `HH` is 00-23, `mm` is 00-59, `ss` is 00-59, and `SSS` is 000-999.
|
||||
|
||||
Special characters (`{leftarrow}`, `{selectall}`, etc) are not permitted.
|
||||
|
||||
## Options
|
||||
|
||||
**Force a click to happen prior to type**
|
||||
|
||||
Prior to typing, if the DOM element isn't currently focused, Cypress issues a [click](https://on.cypress.io/api/click) on the element, which will cause the element to receive focus.
|
||||
|
||||
Sometimes it is useful to force the click to happen in order to disables error checking, like whether the element is currently visible.
|
||||
|
||||
```javascript
|
||||
// this will disable the built-in logic for ensuring
|
||||
// the element is visible, and is physically clickable
|
||||
// prior to typing into it
|
||||
cy.get("input[type=text]").type("Test all the things", {force: true})
|
||||
cy.get('input[type=text]').type('Test all the things', { force: true })
|
||||
```
|
||||
|
||||
{% note warning %}
|
||||
{% note warning %}
|
||||
Be careful with the `force` option because it allows the type to happen where it might actually be impossible for a real user to type.
|
||||
{% endnote %}
|
||||
|
||||
# Key combinations / Modifiers
|
||||
## Key Combinations
|
||||
|
||||
When using special character sequences (see table at top of page), it's possible to activate modifier keys and type key combinations, such as `CTRL + R` or `SHIFT + ALT + Q`. The modifier(s) remain activated for the duration of the `cy.type()` command, and are released when all subsequent characters are typed, unless [`{release: false}`](https://on.cypress.io/api/type#options) is passed as an [option](https://on.cypress.io/v1.0/api/type#release-behavior). A `keydown` event is fired when a modifier is activated and a `keyup` event is fired when it is released.
|
||||
When using special character sequences, it's possible to activate modifier keys and type key combinations, such as `CTRL + R` or `SHIFT + ALT + Q`. The modifier(s) remain activated for the duration of the `.type()` command, and are released when all subsequent characters are typed, unless [`{ release: false }`](https://on.cypress.io/api/type#options) is passed as an [option](https://on.cypress.io/api/type#release-behavior). A `keydown` event is fired when a modifier is activated and a `keyup` event is fired when it is released.
|
||||
|
||||
## Type a key combination
|
||||
**Type a key combination**
|
||||
|
||||
```javascript
|
||||
// this is the same as a user holding down SHIFT and ALT, then pressing Q
|
||||
cy.get("input").type("{shift}{alt}Q")
|
||||
cy.get('input').type('{shift}{alt}Q')
|
||||
```
|
||||
|
||||
{% note info Typing into a login form %}
|
||||
[Check out our example recipe of logging in by typing username and password](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_html_web_form_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
## Hold down modifier key and type a word
|
||||
**Hold down modifier key and type a word**
|
||||
|
||||
```javascript
|
||||
// all characters after {ctrl} will have 'ctrlKey' set to 'true' on their key events
|
||||
cy.get("input").type("{ctrl}test")
|
||||
// all characters after {ctrl} will have 'ctrlKey'
|
||||
// set to 'true' on their key events
|
||||
cy.get('input').type('{ctrl}test')
|
||||
```
|
||||
|
||||
## Release behavior
|
||||
**Release behavior**
|
||||
|
||||
By default, modifiers are released after each type command.
|
||||
|
||||
```javascript
|
||||
// 'ctrlKey' will be true for each event while 'test' is typed
|
||||
// but false while 'everything' is typed
|
||||
cy.get("input").type("{ctrl}test").type("everything")
|
||||
cy.get('input').type('{ctrl}test').type('everything')
|
||||
```
|
||||
|
||||
To keep a modifier activated between commands, specify `{release: false}` in the options.
|
||||
|
||||
```javascript
|
||||
// 'altKey' will be true while typing 'foo'
|
||||
cy.get("input").type("{alt}foo", {release: false})
|
||||
cy.get('input').type('{alt}foo', { release: false })
|
||||
// 'altKey' will also be true during 'get' and 'click' commands
|
||||
cy.get("button").click()
|
||||
cy.get('button').click()
|
||||
```
|
||||
|
||||
Modifiers are automatically released between tests, even with `{release: false}`.
|
||||
|
||||
```javascript
|
||||
it("has modifiers activated", function () {
|
||||
it('has modifiers activated', function () {
|
||||
// 'altKey' will be true while typing 'foo'
|
||||
cy.get("input").type("{alt}foo", {release: false})
|
||||
cy.get('input').type('{alt}foo', {release: false})
|
||||
})
|
||||
|
||||
it("does not have modifiers activated", function () {
|
||||
it('does not have modifiers activated', function () {
|
||||
// 'altKey' will be false while typing 'bar'
|
||||
cy.get("input").type("bar")
|
||||
cy.get('input').type('bar')
|
||||
})
|
||||
```
|
||||
|
||||
@@ -159,68 +238,51 @@ To manually release modifiers within a test after using `{release: false}`, use
|
||||
|
||||
```javascript
|
||||
// 'altKey' will be true while typing 'foo'
|
||||
cy.get("input").type("{alt}foo", {release: false})
|
||||
cy.get('input').type('{alt}foo', {release: false})
|
||||
// 'altKey' will be true during the 'get' and 'click' commands
|
||||
cy.get("button").click()
|
||||
cy.get('button').click()
|
||||
// 'altKey' will be released after this command
|
||||
cy.get("input").type("{alt}")
|
||||
cy.get('input').type('{alt}')
|
||||
// 'altKey' will be false during the 'get' and 'click' commands
|
||||
cy.get("button").click()
|
||||
cy.get('button').click()
|
||||
```
|
||||
|
||||
## Global shortcuts / modifiers
|
||||
## Global Shortcuts
|
||||
|
||||
`cy.type()` requires a focusable element as the subject, since it's usually unintended to type into something that's not a text field or textarea! Although there *are* a few cases where it's valid to "type" into something other than a text field or textarea:
|
||||
`.type()` requires a focusable element as the subject, since it's usually intended to type into something that's an input or textarea. Although there *are* a few cases where it's valid to "type" into something other than an input or textarea:
|
||||
|
||||
* Keyboard shortcuts where the listener is on the `document` or `body`.
|
||||
* Holding modifier keys and clicking an arbitrary element.
|
||||
|
||||
To support this, the `body` can be used as the subject (even though it's *not* a focusable element).
|
||||
To support this, the `body` can be used as the DOM element to type into (even though it's *not* a focusable element).
|
||||
|
||||
**Use keyboard shortcuts in body**
|
||||
|
||||
```javascript
|
||||
// all of the type events will be fired on the body
|
||||
cy.get("body").type("{uparrow}{uparrow}{downarrow}{downarrow}{leftarrow}{rightarrow}{leftarrow}{rightarrow}ba")
|
||||
|
||||
// all of the type events are fired on the body
|
||||
cy.get('body').type('{uparrow}{uparrow}{downarrow}{downarrow}{leftarrow}{rightarrow}{leftarrow}{rightarrow}ba')
|
||||
```
|
||||
|
||||
**Do a shift + click**
|
||||
|
||||
```javascript
|
||||
// execute a SHIFT + click on the first <li>
|
||||
// {release: false} is necessary so that
|
||||
// SHIFT will not be released after the type command
|
||||
cy.get("body").type("{shift}", {release: false}).get("li:first").click()
|
||||
cy.get('body').type('{shift}', {release: false}).get('li:first').click()
|
||||
```
|
||||
|
||||
# Date inputs
|
||||
# Notes
|
||||
|
||||
Using `cy.type()` on a date input (`<input type="date">`) requires specifying a valid date in the format `yyyy-MM-dd`, e.g. `1999-12-31`. This isn't exactly how a user would type into a date input, but is a workaround since date input support varies between browsers and the format varies based on locale. `yyyy-MM-dd` is the format required by [the W3 spec](https://www.w3.org/TR/html/infrastructure.html#sec-dates) and is what the input's `value` will be set to regardless of browser or locale. Special characters (`{leftarrow}`, `{selectall}`, etc) are not permitted.
|
||||
**Typing `tab` key does not work**
|
||||
|
||||
# Month inputs
|
||||
Tabbing will be implemented as a separate command as `cy.tab` and support things like multiple tabs, tabbing in reverse, or tabbing to a specific element. [Open an issue](https://github.com/cypress-io/cypress/issues/new) if you need this to be fixed.
|
||||
|
||||
Using `cy.type()` on a month input (`<input type="month">`) requires specifying a valid month in the format `yyyy-MM`, e.g. `1999-12`. This isn't exactly how a user would type into a month input, but is a workaround since month input support varies between browsers and the format varies based on locale. `yyyy-MM` is the format required by [the W3 spec](https://www.w3.org/TR/html/infrastructure.html#months) and is what the input's `value` will be set to regardless of browser or locale. Special characters (`{leftarrow}`, `{selectall}`, etc) are not permitted.
|
||||
**Preventing `mousedown` does not prevent typing**
|
||||
|
||||
# Week inputs
|
||||
In a real browser, preventing `mousedown` on a form field will prevent it from receiving focus and thus prevent it from being able to be typed into. Currently, Cypress does not factor this in. [Open an issue](https://github.com/cypress-io/cypress/issues/new) if you need this to be fixed.
|
||||
|
||||
Using `cy.type()` on a week input (`<input type="week">`) requires specifying a valid week in the format `yyyy-Www`, where `W` is the literal character 'W' and `ww` is the number of the week (01-53), e.g. `1999-W23` (23rd week of 1999). This isn't exactly how a user would type into a week input, but is a workaround since week input support varies between browsers and the format varies based on locale. `yyyy-Www` is the format required by [the W3 spec](https://www.w3.org/TR/html/infrastructure.html#valid-week-string) and is what the input's `value` will be set to regardless of browser or locale. Special characters (`{leftarrow}`, `{selectall}`, etc) are not permitted.
|
||||
|
||||
# Time inputs
|
||||
|
||||
Using `cy.type()` on a time input (`<input type="time">`) requires specifying a valid time in the format `HH:mm`, `HH:mm:ss`, or `HH:mm:ss.SSS`, where `HH` is 00-23, `mm` is 00-59, `ss` is 00-59, and `SSS` is 000-999. Special characters (`{leftarrow}`, `{selectall}`, etc) are not permitted. The following are examples of valid times:
|
||||
|
||||
* 01:30
|
||||
* 23:15
|
||||
* 12:00:00.384
|
||||
|
||||
# Known Issues
|
||||
|
||||
## Typing `tab` key does not work
|
||||
|
||||
Tabbing will be implemented as a separate command as `cy.tab` and support things like multiple tabs, tabbing in reverse, or tabbing to a specific element. [Open an issue](https://github.com/cypress-io/cypress/issues/new?body=**Description**%0A*Include%20a%20high%20level%20description%20of%20the%20error%20here%20including%20steps%20of%20how%20to%20recreate.%20Include%20any%20benefits%2C%20challenges%20or%20considerations.*%0A%0A**Code**%0A*Include%20the%20commands%20used*%0A%0A**Steps%20To%20Reproduce**%0A-%20%5B%20%5D%20Steps%0A-%20%5B%20%5D%20To%0A-%20%5B%20%5D%20Reproduce%2FFix%0A%0A**Additional%20Info**%0A*Include%20any%20images%2C%20notes%2C%20or%20whatever.*%0A) if you need this to be fixed.
|
||||
|
||||
## Preventing mousedown does not prevent typing
|
||||
|
||||
In a real browser, preventing mousedown on a form field will prevent it from receiving focus and thus prevent it from being able to be typed into. Currently, Cypress does not factor this in. [Open an issue](https://github.com/cypress-io/cypress/issues/new?body=**Description**%0A*Include%20a%20high%20level%20description%20of%20the%20error%20here%20including%20steps%20of%20how%20to%20recreate.%20Include%20any%20benefits%2C%20challenges%20or%20considerations.*%0A%0A**Code**%0A*Include%20the%20commands%20used*%0A%0A**Steps%20To%20Reproduce**%0A-%20%5B%20%5D%20Steps%0A-%20%5B%20%5D%20To%0A-%20%5B%20%5D%20Reproduce%2FFix%0A%0A**Additional%20Info**%0A*Include%20any%20images%2C%20notes%2C%20or%20whatever.*%0A) if you need this to be fixed.
|
||||
|
||||
## Modifier effects
|
||||
**Modifier effects**
|
||||
|
||||
In a real browser, if a user holds `SHIFT` and types `a`, a capital `A` will be typed into the input. Currently, Cypress does not simulate that behavior.
|
||||
|
||||
@@ -228,31 +290,21 @@ Modifiers are simulated by setting their corresponding values to `true` for key
|
||||
|
||||
```javascript
|
||||
// app code
|
||||
document.querySelector("input:first").addEventListener("keydown", function (e) {
|
||||
document.querySelector('input:first').addEventListener('keydown', function (e) {
|
||||
// e.shiftKey will be true
|
||||
})
|
||||
|
||||
// in test
|
||||
cy.get("input:first").type("{shift}a")
|
||||
cy.get('input:first').type('{shift}a')
|
||||
```
|
||||
|
||||
In the example above, a lowercase `a` will be typed, because that's the literal character specified. To type a capital `A`, you can use `cy.type("{shift}A")` (or simply `cy.type("A")` if you don't care about the `shiftKey` property on any key events).
|
||||
In the example above, a lowercase `a` will be typed, because that's the literal character specified. To type a capital `A`, you can use `cy.type('{shift}A')` (or simply `cy.type('A')` if you don't care about the `shiftKey` property on any key events).
|
||||
|
||||
This holds true for other special key combinations as well (that may be OS-specific). For example, on OSX, typing `ALT + SHIFT + K` creates the special character ``. Like with capitalization, `cy.type()` will not output ``, but simply the letter `k`.
|
||||
|
||||
[Open an issue](https://github.com/cypress-io/cypress/issues/new?body=**Description**%0A*Include%20a%20high%20level%20description%20of%20the%20error%20here%20including%20steps%20of%20how%20to%20recreate.%20Include%20any%20benefits%2C%20challenges%20or%20considerations.*%0A%0A**Code**%0A*Include%20the%20commands%20used*%0A%0A**Steps%20To%20Reproduce**%0A-%20%5B%20%5D%20Steps%0A-%20%5B%20%5D%20To%0A-%20%5B%20%5D%20Reproduce%2FFix%0A%0A**Additional%20Info**%0A*Include%20any%20images%2C%20notes%2C%20or%20whatever.*%0A) if you need modifier effects to be implemented.
|
||||
[Open an issue](https://github.com/cypress-io/cypress/issues/new) if you need modifier effects to be implemented.
|
||||
|
||||
# Notes
|
||||
|
||||
## Mimic user typing behavior
|
||||
|
||||
```javascript
|
||||
// each keypress is delayed 10ms by default
|
||||
// which simulates how a very fast user types!
|
||||
cy.get("[contenteditable]").type("some text!")
|
||||
```
|
||||
|
||||
## Events that fire
|
||||
**Events that fire**
|
||||
|
||||
Cypress implements all events that Chrome fires as part of typing in a real keyboard. Read the section: [Simulated Events vs Native Events](#simulated-events-vs-native-events) below for more information.
|
||||
|
||||
@@ -270,7 +322,7 @@ Additionally `change` events will be fired either when the `{enter}` key is pres
|
||||
|
||||
Events that should not fire on non input types such as elements with `tabindex` do not fire their `textInput` or `input` events. Only typing into elements which cause the actual value or text to change will fire those events.
|
||||
|
||||
## Event Firing
|
||||
**Event Firing**
|
||||
|
||||
The following rules have been implemented that match real browser behavior (and the spec):
|
||||
|
||||
@@ -279,23 +331,23 @@ The following rules have been implemented that match real browser behavior (and
|
||||
3. Cypress will fire `textInput` *only* if typing that key would have inserted an actual character.
|
||||
4. Cypress will fire `input` *only* if typing that key modifies or changes the value of the element.
|
||||
|
||||
## Event Cancellation
|
||||
**Event Cancellation**
|
||||
|
||||
Cypress respects all default browser behavior when events are cancelled.
|
||||
|
||||
```javascript
|
||||
// prevent the characters from being inserted
|
||||
// by canceling keydown, keypress, or textInput
|
||||
$("#username").on("keydown", function(e){
|
||||
$('#username').on('keydown', function(e){
|
||||
e.preventDefault();
|
||||
})
|
||||
|
||||
// Cypress will not insert any characters if keydown, keypress, or textInput
|
||||
// are cancelled - which matches the default browser behavior
|
||||
cy.get("#username").type("bob@gmail.com").should("have.value", "") // true
|
||||
cy.get('#username').type('bob@gmail.com').should('have.value', '') // true
|
||||
```
|
||||
|
||||
## Implicit form submission behavior
|
||||
**Implicit form submission behavior**
|
||||
|
||||
Cypress automatically matches the spec and browser behavior for pressing the `{enter}` key when the input belongs to a `<form>`.
|
||||
|
||||
@@ -312,9 +364,8 @@ For instance the following will submit the form.
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("#username").type("bob@burgers.com")
|
||||
.get("#password").type("password123{enter}")
|
||||
cy.get('#username').type('bob@burgers.com')
|
||||
cy.get('#password').type('password123{enter}')
|
||||
```
|
||||
|
||||
Because there are multiple `inputs` and one `submit` button, Cypress submits the form (and fires submit events) as well as a synthetic `click` event to the `button`.
|
||||
@@ -330,19 +381,19 @@ Additionally Cypress handles these 4 other situations as defined in the spec:
|
||||
|
||||
Of course if the form's `submit` event is `preventedDefault` the form will not actually be submitted.
|
||||
|
||||
## Key Events Table
|
||||
**Key Events Table**
|
||||
|
||||
Cypress will print out a table of key events that detail the keys that were pressed when clicking on type within the [command log](https://on.cypress.io/api/type#command-log). Each character will contain the `which` character code and the events that happened as a result of that key press.
|
||||
Cypress prints out a table of key events that detail the keys that were pressed when clicking on type within the [command log](https://on.cypress.io/api/type#command-log). Each character will contain the `which` character code and the events that happened as a result of that key press.
|
||||
|
||||
Events that were `defaultPrevented` may prevent other events from firing and those will show up as empty. For instance, canceling `keydown` will not fire `keypress` or `textInput` or `input`, but will fire `keyup` (which matches the spec).
|
||||
|
||||
Additionally, events that cause a `change` event to fire (such as typing `{enter}`) will display with the `change` event column as `true.
|
||||
Additionally, events that cause a `change` event to fire (such as typing `{enter}`) will display with the `change` event column as `true`.
|
||||
|
||||
Any modifiers activated for the event are also listed in a `modifiers` column.
|
||||
|
||||

|
||||
|
||||
## Simulated Events vs Native Events
|
||||
**Simulated Events vs Native Events**
|
||||
|
||||
When Cypress is running on your local computer, all events are simulated identically to real native events.
|
||||
|
||||
@@ -356,10 +407,10 @@ In other words, you get the best of both worlds: simulated when its practical to
|
||||
|
||||
# Command Log
|
||||
|
||||
## Type into the input
|
||||
**Type into the input**
|
||||
|
||||
```javascript
|
||||
cy.get("input[name=firstName]").type("Jane Lane")
|
||||
cy.get('input[name=firstName]').type('Jane Lane')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -370,8 +421,10 @@ When clicking on `type` within the command log, the console outputs the followin
|
||||
|
||||
<img width="637" alt="screen shot 2015-11-29 at 1 26 24 pm" src="https://cloud.githubusercontent.com/assets/1271364/11459106/f14f3308-969c-11e5-8352-f96744bbd713.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [blur](https://on.cypress.io/api/blur)
|
||||
- [clear](https://on.cypress.io/api/clear)
|
||||
- [click](https://on.cypress.io/api/click)
|
||||
- [focus](https://on.cypress.io/api/focus)
|
||||
- [submit](https://on.cypress.io/api/submit)
|
||||
|
||||
@@ -4,73 +4,97 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Unchecks the checkboxes within the current subject.
|
||||
Uncheck checkbox(es).
|
||||
|
||||
**The following events are fired during uncheck:** `mousedown`, `focus`, `mouseup`, `click`
|
||||
# Syntax
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | `cy.uncheck` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the commands [options](#options). |
|
||||
```javascript
|
||||
.uncheck()
|
||||
.uncheck(value)
|
||||
.uncheck(values)
|
||||
.uncheck(options)
|
||||
.uncheck(value, options)
|
||||
.uncheck(values, options)
|
||||
```
|
||||
|
||||
# [cy.uncheck()](#usage)
|
||||
## Usage
|
||||
|
||||
Unchecks checkboxes. Triggers events associated with check.
|
||||
`.uncheck()` requires being chained off another cy command that *yields* a DOM element of type `checkbox`.
|
||||
|
||||
# [cy.uncheck( *values* )](#values-usage)
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
Unchecks the checkboxes matching the values. Triggers events associated with uncheck.
|
||||
```javascript
|
||||
cy.get('[type="checkbox"]').uncheck() // Yields checkbox element
|
||||
```
|
||||
|
||||
# Options
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.uncheck`.
|
||||
```javascript
|
||||
cy.uncheck('[type="checkbox"]') // Errors, cannot be chained off 'cy'
|
||||
cy.get('p:first').uncheck() // Errors, '.get()' does not yield checkbox
|
||||
```
|
||||
|
||||
**cy.uncheck( *options* )**
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} value** ***(String)***
|
||||
|
||||
Value of checkbox that should be unchecked.
|
||||
|
||||
**{% fa fa-angle-right %} values** ***(Array)***
|
||||
|
||||
Values of checkboxes that should be unchecked.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.uncheck()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`interval` | `16` | Interval which to retry a uncheck
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the uncheck
|
||||
`force` | `false` | Forces uncheck, disables error checking prior to uncheck
|
||||
`interval` | `16` | Interval which to retry a check
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to retry the check
|
||||
`force` | `false` | Forces check, disables error checking prior to check
|
||||
`log` | `true` | whether to display command in command log
|
||||
`multiple` | `false` | Enables serially unchecking multiple elements
|
||||
|
||||
# Usage
|
||||
# Examples
|
||||
|
||||
## Uncheck all checkboxes
|
||||
## Uncheck
|
||||
|
||||
**Uncheck all checkboxes**
|
||||
|
||||
```javascript
|
||||
cy.get(":checkbox").uncheck()
|
||||
cy.get(':checkbox').uncheck()
|
||||
```
|
||||
|
||||
## Uncheck all radios
|
||||
**Uncheck element with the id `saveUserName`**
|
||||
|
||||
```javascript
|
||||
cy.get("[type='checkbox']").uncheck()
|
||||
cy.get('#saveUserName').uncheck()
|
||||
```
|
||||
|
||||
## Uncheck element with the id `saveUserName`
|
||||
## Value
|
||||
|
||||
**Uncheck the checkbox with the value of 'ga'**
|
||||
|
||||
```javascript
|
||||
cy.get("#saveUserName").uncheck()
|
||||
cy.get('input[type="checkbox"]').uncheck(['ga'])
|
||||
```
|
||||
|
||||
# Values Usage
|
||||
## Values
|
||||
|
||||
## Uncheck the checkbox with the value of "ga"
|
||||
**Uncheck the checkboxes with the value of 'ga' and 'ca'**
|
||||
|
||||
```javascript
|
||||
cy.get("input[type='checkbox']").uncheck(["ga"])
|
||||
cy.get('[type="checkbox"]').uncheck(['ga', 'ca'])
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Uncheck the first checkbox
|
||||
**Uncheck the first checkbox**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.get("[data-js='choose-all']").click()
|
||||
.find("input[type='checkbox']").first().uncheck()
|
||||
.get('[data-js="choose-all"]').click()
|
||||
.find('input[type="checkbox"]').first().uncheck()
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -81,7 +105,7 @@ When clicking on `uncheck` within the command log, the console outputs the follo
|
||||
|
||||
<img width="601" alt="screen shot 2015-11-29 at 1 31 04 pm" src="https://cloud.githubusercontent.com/assets/1271364/11459134/7f29dea8-969d-11e5-9843-dfd07dfe888f.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [check](https://on.cypress.io/api/check)
|
||||
- [click](https://on.cypress.io/api/click)
|
||||
|
||||
@@ -4,59 +4,78 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the current URL. `cy.url()` uses [`cy.location.href`](https://on.cypress.io/api/location) under the hood.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the current URL as a string |
|
||||
| **Timeout** | *cannot timeout* |
|
||||
|
||||
# [cy.url()](#usage)
|
||||
|
||||
Get the current URL.
|
||||
|
||||
# Options
|
||||
{% note info %}
|
||||
This is the same as [`cy.location.href`](https://on.cypress.io/api/location)
|
||||
{% endnote %}
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.url`.
|
||||
# Syntax
|
||||
|
||||
**cy.url( *options* )**
|
||||
```javascript
|
||||
cy.url()
|
||||
cy.url(options)
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`cy.url()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.url()
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.url()`.
|
||||
|
||||
**cy.hash( *options* )**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Assert the URL is `http://localhost:8000/users/1/edit`
|
||||
`.url()` yields the current URL as a string.
|
||||
|
||||
## Timeout
|
||||
|
||||
# Examples
|
||||
|
||||
## Url
|
||||
|
||||
**Assert the URL is `http://localhost:8000/users/1/edit`**
|
||||
|
||||
```javascript
|
||||
// clicking the anchor causes the browser to follow the link
|
||||
cy
|
||||
.get("#user-edit a").click()
|
||||
.url().should("eq", "http://localhost:8000/users/1/edit") // => true
|
||||
cy.get('#user-edit a').click()
|
||||
cy.url().should('eq', 'http://localhost:8000/users/1/edit') // => true
|
||||
```
|
||||
|
||||
## URL is a shortcut for `cy.location().href`
|
||||
**Url is a shortcut for `cy.location().href`**
|
||||
|
||||
`cy.url()` uses `href` under the hood.
|
||||
|
||||
```javascript
|
||||
cy.url() // these return the same string
|
||||
cy.location().its("href") // these return the same string
|
||||
cy.url() // these yield the same string
|
||||
cy.location().its('href') // these yield the same string
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
## Why is this command called `url` instead of `href`?
|
||||
**Url versus href**
|
||||
|
||||
Given the remote URL, `http://localhost:8000/index.html`, all 3 of these assertions are the same.
|
||||
|
||||
```javascript
|
||||
cy.location().its("href").should("eq", "http://localhost:8000/index.html")
|
||||
cy.location().its('href').should('eq', 'http://localhost:8000/index.html')
|
||||
|
||||
cy.location().invoke("toString").should("eq", "http://localhost:8000/index.html")
|
||||
cy.location().invoke('toString').should('eq', 'http://localhost:8000/index.html')
|
||||
|
||||
cy.url().should("eq", "http://localhost:8000/index.html")
|
||||
cy.url().should('eq', 'http://localhost:8000/index.html')
|
||||
```
|
||||
|
||||
`href` and `toString` come from the `window.location` spec.
|
||||
@@ -67,10 +86,10 @@ But you may be wondering where the `url` property comes from. Per the `window.l
|
||||
|
||||
# Command Log
|
||||
|
||||
## Assert that the url contains "#users/new"
|
||||
**Assert that the url contains "#users/new"**
|
||||
|
||||
```javascript
|
||||
cy.url().should("contain", "#users/new")
|
||||
cy.url().should('contain', '#users/new')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -81,7 +100,9 @@ When clicking on `url` within the command log, the console outputs the following
|
||||
|
||||
<img width="440" alt="screen shot 2015-11-29 at 1 42 52 pm" src="https://cloud.githubusercontent.com/assets/1271364/11459197/229e2552-969f-11e5-80a9-eeaf3221a178.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [document](https://on.cypress.io/api/document)
|
||||
- [hash](https://on.cypress.io/api/hash)
|
||||
- [location](https://on.cypress.io/api/location)
|
||||
- [window](https://on.cypress.io/api/window)
|
||||
|
||||
@@ -4,20 +4,45 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Use `cy.viewport` to control the screen size and orientation of your application. This command is useful for when you need to test your application in a specific width or height, such as responsive applications or applications utilizing media queries. `cy.viewport` width and height must be between 200px and 3000px.
|
||||
Control the size and orientation of the screen for your application.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | `null` |
|
||||
| **Timeout** | *cannot timeout* |
|
||||
{% note info %}
|
||||
You can set the viewport's width and height globally by defining `viewportWidth` and `viewportHeight` in the [configuration](https://on.cypress.io/guides/configuration).
|
||||
{% endnote %}
|
||||
|
||||
# [cy.viewport( *width*, *height* )](#usage)
|
||||
# Syntax
|
||||
|
||||
Resize the viewport to the specified dimensions in pixels.
|
||||
```javascript
|
||||
cy.viewport(width, height)
|
||||
cy.viewport(preset, orientation)
|
||||
cy.viewport(width, height, options)
|
||||
cy.viewport(preset, orientation, options)
|
||||
```
|
||||
|
||||
# [cy.viewport( *preset*, *orientation* )](#preset-usage)
|
||||
## Usage
|
||||
|
||||
Resize the viewport to a preset dimension. Viewport supports the following presets (in pixels):
|
||||
`cy.viewport()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.viewport(550, 750)
|
||||
cy.viewport('iphone-6')
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} width** ***(Number)***
|
||||
|
||||
Width of viewport in pixels (must be between 200 and 3000).
|
||||
|
||||
**{% fa fa-angle-right %} height** ***(Number)***
|
||||
|
||||
Height of viewport in pixels (must be between 200 and 3000).
|
||||
|
||||
**{% fa fa-angle-right %} preset** ***(String)***
|
||||
|
||||
A preset dimension (in pixels) to set the viewport. Preset supports the following options:
|
||||
|
||||
| Preset | width | height |
|
||||
| ----------- | ----- | ------ |
|
||||
@@ -32,119 +57,121 @@ Resize the viewport to a preset dimension. Viewport supports the following prese
|
||||
| `iphone-4` | 320 | 480 |
|
||||
| `iphone-3` | 320 | 480 |
|
||||
|
||||
The **default orientation** is `portrait`. Pass `landscape` as the orientation to reverse the width/height.
|
||||
**{% fa fa-angle-right %} orientation** ***(String)***
|
||||
|
||||
# Options
|
||||
The orientation of the screen. The *default orientation* is `portrait`. Pass `landscape` as the orientation to reverse the width/height.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.viewport`.
|
||||
|
||||
**cy.viewport( *width*, *height*, *options* )**
|
||||
**cy.viewport( *preset*, *orientation*, *options* )**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
You can also set options for the viewport's `viewportWidth` and `viewportHeight` globally in [configuration](https://on.cypress.io/guides/configuration).
|
||||
## Yields
|
||||
|
||||
# Usage
|
||||
`.viewport()` yields `null`.
|
||||
|
||||
## Resize the viewport to 1024 x 768
|
||||
## Timeout
|
||||
|
||||
# Examples
|
||||
|
||||
## Width, Height
|
||||
|
||||
**Resize the viewport to 1024px x 768px**
|
||||
|
||||
```javascript
|
||||
// the viewport will now be changed to 1024x768 pixels
|
||||
cy.viewport(1024, 768)
|
||||
```
|
||||
|
||||
## Organize desktop vs mobile tests separately
|
||||
**Organize desktop vs mobile tests separately**
|
||||
|
||||
```javascript
|
||||
describe("Nav Menus", function(){
|
||||
context("720p resolution", function(){
|
||||
describe('Nav Menus', function(){
|
||||
context('720p resolution', function(){
|
||||
beforeEach(function(){
|
||||
// run these tests in a desktop browser
|
||||
// with a 720p monitor
|
||||
// run these tests as if in a desktop
|
||||
// browser with a 720p monitor
|
||||
cy.viewport(1280, 720)
|
||||
})
|
||||
|
||||
it("displays full header", function(){
|
||||
cy
|
||||
.get("nav .desktop-menu").should("be.visible")
|
||||
.get("nav .mobile-menu").should("not.be.visible")
|
||||
it('displays full header', function(){
|
||||
cy.get('nav .desktop-menu').should('be.visible')
|
||||
cy.get('nav .mobile-menu').should('not.be.visible')
|
||||
})
|
||||
})
|
||||
|
||||
context("iphone-5 resolution", function(){
|
||||
context('iphone-5 resolution', function(){
|
||||
beforeEach(function(){
|
||||
// run these tests in a mobile browser
|
||||
// run these tests as if in a mobile browser
|
||||
// and ensure our responsive UI is correct
|
||||
cy.viewport("iphone-5")
|
||||
cy.viewport('iphone-5')
|
||||
})
|
||||
|
||||
it("displays mobile menu on click", function(){
|
||||
cy
|
||||
.get("nav .desktop-menu").should("not.be.visible")
|
||||
.get("nav .mobile-menu")
|
||||
.should("be.visible")
|
||||
.find("i.hamburger").click()
|
||||
.get("ul.slideout-menu").should("be.visible")
|
||||
it('displays mobile menu on click', function(){
|
||||
cy.get('nav .desktop-menu').should('not.be.visible')
|
||||
cy.get('nav .mobile-menu')
|
||||
.should('be.visible')
|
||||
.find('i.hamburger').click()
|
||||
cy.get('ul.slideout-menu').should('be.visible')
|
||||
})
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
# Preset Usage
|
||||
## Preset
|
||||
|
||||
## Resize the viewport to iPhone 6 width and height
|
||||
**Resize the viewport to iPhone 6 width and height**
|
||||
|
||||
```javascript
|
||||
// the viewport will now be changed to 414x736
|
||||
cy.viewport("iphone-6")
|
||||
|
||||
cy.viewport('iphone-6') // viewport will change to 414px x 736px
|
||||
```
|
||||
|
||||
## Change the orientation to landscape
|
||||
## Orientation
|
||||
|
||||
**Change the orientation to landscape**
|
||||
|
||||
```javascript
|
||||
// the viewport will now be changed to 736x414
|
||||
// which simulates the user holding the iPhone in lanscape
|
||||
cy.viewport("iphone-6", "landscape")
|
||||
// the viewport will now be changed to 736px x 414px
|
||||
// and simulates the user holding the iPhone in landscape
|
||||
cy.viewport('iphone-6', 'landscape')
|
||||
```
|
||||
|
||||
# Known Issues
|
||||
|
||||
## `devicePixelRatio` is not simulated
|
||||
|
||||
This is something Cypress will eventually do, which will match how Chrome's responsive mobile browsing simulation works. [Open an issue](https://github.com/cypress-io/cypress/issues/new?body=**Description**%0A*Include%20a%20high%20level%20description%20of%20the%20error%20here%20including%20steps%20of%20how%20to%20recreate.%20Include%20any%20benefits%2C%20challenges%20or%20considerations.*%0A%0A**Code**%0A*Include%20the%20commands%20used*%0A%0A**Steps%20To%20Reproduce**%0A-%20%5B%20%5D%20Steps%0A-%20%5B%20%5D%20To%0A-%20%5B%20%5D%20Reproduce%2FFix%0A%0A**Additional%20Info**%0A*Include%20any%20images%2C%20notes%2C%20or%20whatever.*%0A) if you need this to be fixed.
|
||||
|
||||
# Notes
|
||||
|
||||
## Cypress will restore the viewport for each command
|
||||
**`devicePixelRatio` is not simulated**
|
||||
|
||||
When hovering over each command, Cypress will automatically restore the viewport to the dimensions that existed when that command ran.
|
||||
This is something Cypress will eventually do, which will match how Chrome's responsive mobile browsing simulation works. [Open an issue](https://github.com/cypress-io/cypress/issues/new) if you need this to be fixed.
|
||||
|
||||
## Default sizing
|
||||
**Cypress will restore the viewport in the snapshot**
|
||||
|
||||
By default, until you issue a `cy.viewport` command, Cypress will assume the width is: `1000px` and the height is `660px`.
|
||||
When hovering over each command, Cypress will automatically display the snapshot in the viewport dimensions that existed when that command ran.
|
||||
|
||||
**Default sizing**
|
||||
|
||||
By default, until you issue a `cy.viewport()` command, Cypress sets the width to `1000px` and the height to `660px` by default.
|
||||
|
||||
You can [change these default dimensions](https://on.cypress.io/guides/configuration) by adding the following to your `cypress.json`
|
||||
|
||||
```javascript
|
||||
```json
|
||||
{
|
||||
viewportWidth: 1000,
|
||||
viewportHeight: 660
|
||||
"viewportWidth": 1000,
|
||||
"viewportHeight": 660
|
||||
}
|
||||
```
|
||||
|
||||
Additionally, Cypress automatically sets the viewport to it's default size between each test.
|
||||
|
||||
## Auto Scaling
|
||||
**Auto Scaling**
|
||||
|
||||
By default, if your screen is not large enough to display all of the current dimension's pixels, Cypress will scale and center your application within Cypress to accommodate.
|
||||
By default, if your screen is not large enough to display all of the current dimension's pixels, Cypress will scale and center your application within the Cypress runner to accommodate.
|
||||
|
||||
Scaling the app should not affect any calculations or behavior of your application (in fact it won't even know it's being scaled).
|
||||
|
||||
The upsides to this is that tests should consistently pass or fail regardless of each of your developers' screen sizes. Tests will also consistently run in `CI` because all of the viewports will be the same no matter what machine Cypress runs on.
|
||||
The upsides to this are that tests should consistently pass or fail regardless of a developers' screen size. Tests will also consistently run in `CI` because all of the viewports will be the same no matter what machine Cypress runs on.
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [Configuration](https://on.cypress.io/guides/configuration)
|
||||
|
||||
@@ -4,26 +4,36 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Visit a remote url. This will most likely be the first command you run. `cy.visit` resolves when the remote page fires its `load` event.
|
||||
Visit a remote url.
|
||||
|
||||
Visit is prefixed with the `baseUrl` configured in the [Network Options](https://on.cypress.io/guides/configuration#global).
|
||||
# Syntax
|
||||
|
||||
Using `baseUrl` is a great way to prevent repeating yourself in every `cy.visit`.
|
||||
```javascript
|
||||
cy.visit(url)
|
||||
cy.visit(url, options)
|
||||
```
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the remote page's window object |
|
||||
| **Timeout** | `cy.visit` will retry for the duration of the [pageLoadTimeout](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's [options](#options). |
|
||||
`cy.visit` resolves when the remote page fires its `load` event.
|
||||
|
||||
# [cy.visit( *url* )](#usage)
|
||||
## Usage
|
||||
|
||||
Visit the specified url passed as a string.
|
||||
`cy.visit()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
# Options
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.visit`.
|
||||
```javascript
|
||||
cy.visit('http://localhost:3000')
|
||||
```
|
||||
|
||||
**[cy.visit( *url*, *options* )](#options-usage)**
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} url** ***(String)***
|
||||
|
||||
The url to visit. The url provided will be prefixed with the `baseUrl` configured in your [network options](https://on.cypress.io/guides/configuration#global).
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.visit()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
@@ -32,93 +42,97 @@ Option | Default | Notes
|
||||
`timeout` | [pageLoadTimeout](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait until `cy.visit` resolves
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
You can also set options for all `cy.visit` `pageLoadTimeout` and `baseUrl` globally in [configuration](https://on.cypress.io/guides/configuration).
|
||||
You can also set all `cy.visit()` commands' `pageLoadTimeout` and `baseUrl` globally in [configuration](https://on.cypress.io/guides/configuration).
|
||||
|
||||
# Usage
|
||||
|
||||
## Visit a local server running on http://localhost:8000
|
||||
## Yields
|
||||
|
||||
`cy.visit()` yields the remote `window` object.
|
||||
|
||||
## Timeout
|
||||
|
||||
`cy.visit` will retry for the duration of the [pageLoadTimeout](https://on.cypress.io/guides/configuration#timeouts) or the duration of the `timeout` specified in the command's [options](#options).
|
||||
|
||||
# Examples
|
||||
|
||||
## Visit
|
||||
|
||||
**Visit a local server running on http://localhost:8000**
|
||||
|
||||
```javascript
|
||||
cy.visit("http://localhost:8000")
|
||||
cy.visit('http://localhost:8000')
|
||||
```
|
||||
|
||||
## Protocol can be omitted from common hosts
|
||||
**Protocol can be omitted from common hosts**
|
||||
|
||||
Cypress automatically prepends the `http://` protocol to common hosts. If you're not using one of these 3 hosts, then make sure to provide the protocol.
|
||||
|
||||
```javascript
|
||||
// Cypress will automatically prepend the http:// protocol
|
||||
// to common hosts. If you're not using one of these
|
||||
// 3 hosts, then make sure to provide the protocol
|
||||
cy.visit("localhost:3000") // => http://localhost:3000
|
||||
cy.visit("0.0.0.0:3000") // => http://0.0.0.0:3000
|
||||
cy.visit("127.0.0.1:3000") // => http://127.0.0.1:3000
|
||||
cy.visit('localhost:3000') // Visits http://localhost:3000
|
||||
cy.visit('0.0.0.0:3000') // Visits http://0.0.0.0:3000
|
||||
cy.visit('127.0.0.1:3000') // Visits http://127.0.0.1:3000
|
||||
```
|
||||
|
||||
## Cypress can optionally act as your web server
|
||||
**Cypress can optionally act as your web server**
|
||||
|
||||
Cypress will automatically attempt to serve your files if you don't provide a host. The path should be relative to your project's root folder (where `cypress.json` is located).
|
||||
|
||||
Having Cypress serve your files is useful in simple projects and example apps, but isn't recommended for real apps. It is always better to run your own server and provide the url to Cypress.
|
||||
|
||||
```javascript
|
||||
// Cypress will automatically attempt to serve your files
|
||||
// if you do not provide a host. The path should be relative
|
||||
// to your project's root folder. The root folder is
|
||||
// where cypress.json is stored.
|
||||
cy.visit("app/index.html")
|
||||
cy.visit('app/index.html')
|
||||
```
|
||||
|
||||
## Visit is automatically prefixed with `baseUrl`.
|
||||
**Visit is automatically prefixed with `baseUrl`.**
|
||||
|
||||
Simply configure `baseUrl` in the `cypress.json` file to prevent repeating yourself in every single `cy.visit(...)`. Read more about [`configuration`](https://on.cypress.io/guides/configuration).
|
||||
Configure `baseUrl` in the `cypress.json` file to prevent repeating yourself in every single `cy.visit()` command. Read more about [`configuration`](https://on.cypress.io/guides/configuration).
|
||||
|
||||
```javascript
|
||||
// cypress.json
|
||||
```json
|
||||
{
|
||||
baseUrl: "http://localhost:3000/#/"
|
||||
"baseUrl": "http://localhost:3000/#/"
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// this will visit the complete url
|
||||
// http://localhost:3000/#/dashboard
|
||||
cy.visit("dashboard")
|
||||
cy.visit('dashboard') // Visits http://localhost:3000/#/dashboard
|
||||
```
|
||||
|
||||
# Options Usage
|
||||
## Options
|
||||
|
||||
## Change the default timeout
|
||||
**Change the default timeout**
|
||||
|
||||
```javascript
|
||||
// change the timeout to be 30 seconds
|
||||
cy.visit("/index.html", {timeout: 30000})
|
||||
// Wait 30 seconds for page 'load' event
|
||||
cy.visit('/index.html', { timeout: 30000 })
|
||||
```
|
||||
|
||||
## Provide an `onBeforeLoad` callback function
|
||||
**Provide an `onBeforeLoad` callback function**
|
||||
|
||||
`onBeforeLoad` is called as soon as possible, before your page has loaded all of its resources. Your scripts will not be ready at this point, but it's a great hook to potentially manipulate the page.
|
||||
|
||||
```javascript
|
||||
// onBeforeLoad is called as soon as possible, before
|
||||
// your page has loaded all of its resources. Your scripts
|
||||
// will not be ready at this point, but it's a great hook
|
||||
// to potentially manipulate the page.
|
||||
cy.visit("http://localhost:3000/#dashboard", {
|
||||
cy.visit('http://localhost:3000/#dashboard', {
|
||||
onBeforeLoad: function(contentWindow){
|
||||
// contentWindow is the remote page's window object
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
{% note info Using onBeforeLoad %}
|
||||
Check out our example recipes using cy.visit's onBeforeLoad option to [help bootstrap app data](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/bootstrapping_app_test_data_spec.js), to [set a token to localStorage for login](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_single_sign_on_spec.js) and to [stub window.fetch](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/spy_stub_clock_spec.js)
|
||||
**Using onBeforeLoad**
|
||||
|
||||
{% note info %}
|
||||
Check out our example recipes using `cy.visit`'s `onBeforeLoad` option to [help bootstrap app data](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/bootstrapping_app_test_data_spec.js), to [set a token to localStorage for login](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_single_sign_on_spec.js) and to [stub window.fetch](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/spy_stub_clock_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
## Provide an `onLoad` callback function
|
||||
**Provide an `onLoad` callback function**
|
||||
|
||||
`onLoad` is called once your page has fires its `load` event. All of the scripts, stylesheets, html and other resources are guaranteed to be available at this point.
|
||||
|
||||
```javascript
|
||||
// onLoad is called once your page has fired its load event.
|
||||
// all of the scripts, stylesheets, html and other resources
|
||||
// are guaranteed to be available at this point.
|
||||
cy.visit("http://localhost:3000/#/users", {
|
||||
cy.visit('http://localhost:3000/#/users', {
|
||||
onLoad: function(contentWindow){
|
||||
// contentWindow is the remote page's window object
|
||||
if(contentWindow.angular){
|
||||
if (contentWindow.angular) {
|
||||
// do something
|
||||
}
|
||||
}
|
||||
@@ -127,75 +141,55 @@ cy.visit("http://localhost:3000/#/users", {
|
||||
|
||||
# Notes
|
||||
|
||||
## Visit will always yield the remote page's window object when it resolves
|
||||
**Visit will always yield the remote page's window object when it resolves**
|
||||
|
||||
```javascript
|
||||
cy.visit("index.html").then(function(contentWindow)){
|
||||
cy.visit('index.html').then(function(contentWindow)){
|
||||
// contentWindow is the remote page's window object
|
||||
})
|
||||
```
|
||||
|
||||
## Visit will automatically follow redirects
|
||||
**Visit will automatically follow redirects**
|
||||
|
||||
```javascript
|
||||
// we aren't logged in, and our webserver
|
||||
// redirects us to /login
|
||||
cy
|
||||
.visit("http://localhost3000/admin")
|
||||
.url().should("match", /login/)
|
||||
// we aren't logged in, so our webserver
|
||||
// redirected us to /login
|
||||
cy.visit('http://localhost3000/admin')
|
||||
cy.url().should('match', /login/)
|
||||
```
|
||||
|
||||
## Cypress automatically wipes page state between visits
|
||||
|
||||
Whenever you `cy.visit()`, Cypress will automatically wipe the state of the page before navigating to an external page.
|
||||
|
||||
Internally Cypress will visit `about:blank` which flushes the window.
|
||||
|
||||
```javascript
|
||||
// internally this does the following:
|
||||
// visit 'dashboard'
|
||||
// visit 'about:blank'
|
||||
// visit 'users'
|
||||
cy
|
||||
.visit("dashboard")
|
||||
|
||||
...more commands...
|
||||
|
||||
.visit("users")
|
||||
|
||||
```
|
||||
|
||||
## Preventing XHR / AJAX requests before a remote page initially loads
|
||||
**Preventing XHR / AJAX 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.
|
||||
|
||||
You may think this works:
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.visit("http://localhost:8000/#/app")
|
||||
.server()
|
||||
.route(/users/, {...})
|
||||
// this code may not work depending on implementation
|
||||
cy.visit('http://localhost:8000/#/app')
|
||||
cy.server()
|
||||
cy.route('/users/**', 'fx: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 `server` and `route` commands are not processed until *after* `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 `server` and `route` commands are not processed until *after* `cy.visit()` resolves.
|
||||
|
||||
Many applications will have already begun routing, initialization, and requests by the time `visit` resolves. Therefore creating a `cy.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 `cy.server` will happen too late, and Cypress will not process the requests.
|
||||
|
||||
Luckily Cypress supports this use case easily. Simply reverse the order of the commands:
|
||||
Luckily Cypress supports this use case. Simply reverse the order of the commands:
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route(/users/, {...})
|
||||
.visit("http://localhost:8000/#/app")
|
||||
// this code is probably want you want
|
||||
cy.server()
|
||||
cy.route('/users/**', {...})
|
||||
cy.visit('http://localhost:8000/#/app')
|
||||
```
|
||||
|
||||
Cypress will automatically apply the server and routes to the very next `visit` and does so immediately before any of your application code runs.
|
||||
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.
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [go](https://on.cypress.io/api/go)
|
||||
- [Recipe: Bootstrapping App Test Data](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/bootstrapping_app_test_data_spec.js)
|
||||
- [Recipe: Logging In - Single Sign on](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_single_sign_on_spec.js)
|
||||
- [go](https://on.cypress.io/api/go)
|
||||
- [request](https://on.cypress.io/api/request)
|
||||
- [server](https://on.cypress.io/api/server)
|
||||
|
||||
@@ -4,131 +4,195 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Use `cy.wait` to wait for a number of milliseconds or for a resource to resolve.
|
||||
Wait for a number of milliseconds or wait for an aliased resource to resolve before moving on to the next command.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the current subject if waiting for number of milliseconds, the xhr object if waiting for a route |
|
||||
| **Timeout** | `cy.wait` will wait for the request the duration of the [requestTimeout](https://on.cypress.io/guides/configuration#timeouts) and wait for the response for the duration of the [responseTimeout](https://on.cypress.io/guides/configuration#timeouts) or it will wait for both the duration request and response for the `timeout` specified in the command's [options](#options).|
|
||||
|
||||
# [cy.wait( *number* )](#number-usage)
|
||||
# Syntax
|
||||
|
||||
Wait a specific amount of `ms` before resolving and continuing onto the next command.
|
||||
```javascript
|
||||
cy.wait(time)
|
||||
cy.wait(alias)
|
||||
cy.wait(aliases)
|
||||
cy.wait(time, options)
|
||||
cy.wait(alias, options)
|
||||
cy.wait(aliases, options)
|
||||
```
|
||||
|
||||
# [cy.wait( *alias* )](#alias-usage)
|
||||
## Usage
|
||||
|
||||
Wait until the matching [aliased](https://on.cypress.io/guides/using-aliases) XHR has a response.
|
||||
`cy.wait()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
{% note info New to Cypress? %}
|
||||
Read about [Network Requests](https://on.cypress.io/guides/network-requests-xhr) and [Aliasing](https://on.cypress.io/guides/using-aliases) first.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.wait(500)
|
||||
cy.wait('@getProfile')
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} time** ***(Number)***
|
||||
|
||||
The amount of time to wait in milliseconds.
|
||||
|
||||
**{% fa fa-angle-right %} alias** ***(String)***
|
||||
|
||||
An aliased route as defined using the [`.as()`](https://on.cypress.io/api/as) command and referenced with the `@` character and the name of the alias.
|
||||
|
||||
{% note info %}
|
||||
[Read about using aliases here.](https://on.cypress.io/guides/using-aliases)
|
||||
{% endnote %}
|
||||
|
||||
# [cy.wait( *\[alias1*, *alias2*, *alias3\]* )](#alias-array-usage)
|
||||
**{% fa fa-angle-right %} aliases** ***(Array)***
|
||||
|
||||
Wait for an array of [aliases](https://on.cypress.io/guides/using-aliases) to have responses.
|
||||
An array of aliased routes as defined using the [`.as()`](https://on.cypress.io/api/as) command and referenced with the `@` character and the name of the alias.
|
||||
|
||||
# Options
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.wait`.
|
||||
|
||||
**[cy.wait( *text*, *options* )](#options-usage)**
|
||||
Pass in an options object to change the default behavior of `cy.wait()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`timeout` | [requestTimeout](https://on.cypress.io/guides/configuration#timeouts), [responseTimeout](https://on.cypress.io/guides/configuration#timeouts) | Override the default requestTimeout and responseTimeout (in ms)
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
You can also change the default `requestTimeout` and `responseTimeout` that all `cy.wait` use in [configuration](https://on.cypress.io/guides/configuration).
|
||||
You can also change the `requestTimeout` and `responseTimeout` globally for all `cy.wait()` commands in the [configuration](https://on.cypress.io/guides/configuration).
|
||||
|
||||
# Number Usage
|
||||
## Yields
|
||||
|
||||
## Wait 500ms
|
||||
When given a `time` argument, `.wait()` yields the previous commands yield.
|
||||
|
||||
When given an `alias` argument, `.wait()` yields the xhr object of the aliased route.
|
||||
|
||||
## Timeout
|
||||
|
||||
`cy.wait` will wait for the request the duration of the [requestTimeout](https://on.cypress.io/guides/configuration#timeouts) and wait for the response for the duration of the [responseTimeout](https://on.cypress.io/guides/configuration#timeouts) or it will wait for the duration of both the request and response for the `timeout` specified in the command's [options](#options).
|
||||
|
||||
# Examples
|
||||
|
||||
## Time
|
||||
|
||||
In Cypress, you almost never need to use `cy.wait()` for an arbitrary amount of time. If you are finding yourself doing this, there is likely a much better, simpler way.
|
||||
|
||||
**Let's imagine the following examples:**
|
||||
|
||||
***Unnecessary wait for `cy.request`***
|
||||
|
||||
Waiting here is unnecessary since the `cy.request` command will not resolve until it receives a response from your server. Adding the wait here only adds 5 seconds after the `cy.request()` has already resolved.
|
||||
|
||||
```javascript
|
||||
// Wait 500ms before resolving
|
||||
cy.wait(500)
|
||||
cy.request("http://localhost:8080/db/seed")
|
||||
cy.wait(5000) // <--- this is unnecessary
|
||||
```
|
||||
|
||||
# Alias Usage
|
||||
***Unnecessary wait for `cy.visit`***
|
||||
|
||||
## Wait for a specific XHR to respond
|
||||
Waiting for this is unnecessary because the `cy.visit()` resolves once the page fires its `load` event. By that time all of your assets have been loaded including javascript, stylesheets, and html.
|
||||
|
||||
```javascript
|
||||
cy.visit("http://localhost/8080")
|
||||
cy.wait(5000) // <--- this is unnecessary
|
||||
```
|
||||
|
||||
***Unnecessary wait for `cy.get`***
|
||||
|
||||
Waiting for the `cy.get()` below is unncessary because `cy.get()` automatically retries until the table's `tr` has a length of 2.
|
||||
|
||||
Whenever commands have an assertion they will not resolve until their associated assertions pass. This enables you to simply describe the state of your application without having to worry about when it gets there.
|
||||
|
||||
```javascript
|
||||
cy.server()
|
||||
cy.route("GET", /users/, [{"name": "Maggy"}, {"name": "Joan"}])
|
||||
cy.get("#fetch").click()
|
||||
cy.wait(4000) // <--- this is unnecessary
|
||||
cy.get("table tr").should("have.length", 2)
|
||||
```
|
||||
|
||||
Alternatively a better solution to this problem is by waiting explicitly for an aliased route.
|
||||
|
||||
```javascript
|
||||
cy.server()
|
||||
cy.route("GET", /users/, [{"name": "Maggy"}, {"name": "Joan"}]).as("getUsers")
|
||||
cy.get("#fetch").click()
|
||||
cy.wait("@getUsers") // <--- wait explicitly for this route to finish
|
||||
cy.get("table tr").should("have.length", 2)
|
||||
```
|
||||
|
||||
## Alias
|
||||
|
||||
**Wait for a specific XHR to respond**
|
||||
|
||||
```javascript
|
||||
// Wait for the route aliased as 'getAccount' to respond
|
||||
// without changing or stubbing its response
|
||||
cy
|
||||
.server()
|
||||
.route(/accounts\/d+/).as("getAccount")
|
||||
.visit("/accounts/123")
|
||||
.wait("@getAccount").then(function(xhr){
|
||||
.route('/accounts/*').as('getAccount')
|
||||
.visit('/accounts/123')
|
||||
.wait('@getAccount').then(function(xhr){
|
||||
// we can now access the low level xhr
|
||||
// that contains the request body,
|
||||
// response body, status, etc
|
||||
})
|
||||
```
|
||||
|
||||
## Wait automatically increments responses
|
||||
**Wait automatically increments responses**
|
||||
|
||||
Each time we use `cy.wait()` for an alias, Cypress waits for the next nth matching request.
|
||||
|
||||
```javascript
|
||||
// each time we cy.wait() for an alias, Cypress will
|
||||
// wait for the next nth matching request
|
||||
cy
|
||||
.server()
|
||||
.route(/books/, []).as("getBooks")
|
||||
.get("#search").type("Grendel")
|
||||
cy.server()
|
||||
cy.route('/books', []).as('getBooks')
|
||||
cy.get('#search').type('Grendel')
|
||||
|
||||
// wait for the first response to finish
|
||||
.wait("@getBooks")
|
||||
// wait for the first response to finish
|
||||
cy.wait('@getBooks')
|
||||
|
||||
// the results should be empty because we
|
||||
// responded with an empty array first
|
||||
.get("#book-results").should("be.empty")
|
||||
// the results should be empty because we
|
||||
// responded with an empty array first
|
||||
cy.get('#book-results').should('be.empty')
|
||||
|
||||
// now re-route the books endpoint and force it to
|
||||
// have a response this time
|
||||
.route(/books/, [{name: "Emperor of all maladies"}])
|
||||
// now re-define the /books response
|
||||
cy.route('/books', [{name: 'Emperor of all maladies'}])
|
||||
|
||||
.get("#search").type("Emperor of")
|
||||
cy.get('#search').type('Emperor of')
|
||||
|
||||
// now when we wait for 'getBooks' again, Cypress will
|
||||
// automatically know to wait for the 2nd response
|
||||
.wait("@getBooks")
|
||||
// now when we wait for 'getBooks' again, Cypress will
|
||||
// automatically know to wait for the 2nd response
|
||||
cy.wait('@getBooks')
|
||||
|
||||
// we responded with 1 book item so now we should
|
||||
// have one result
|
||||
.get("#book-results").should("have.length", 1)
|
||||
// we responded with 1 book item so now we should
|
||||
// have one result
|
||||
cy.get('#book-results').should('have.length', 1)
|
||||
```
|
||||
|
||||
# Alias Array Usage
|
||||
## Aliases
|
||||
|
||||
## You can pass an array of aliases that will be waited on before resolving.
|
||||
**You can pass an array of aliases that will be waited on before resolving.**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route(/users/).as("getUsers")
|
||||
.route(/activities/).as("getActivities")
|
||||
.route(/comments/).as("getComments")
|
||||
.visit("/dashboard")
|
||||
cy.server()
|
||||
cy.route('users/*').as('getUsers')
|
||||
cy.route('activities/*').as('getActivities')
|
||||
cy.route('comments/*').as('getComments')
|
||||
cy.visit('/dashboard')
|
||||
|
||||
.wait(["@getUsers", "@getActivities", "getComments"])
|
||||
.then(function(xhrs){
|
||||
// xhrs will now be an array of matching XHR's
|
||||
// xhrs[0] <-- getUsers
|
||||
// xhrs[1] <-- getActivities
|
||||
// xhrs[2] <-- getComments
|
||||
})
|
||||
cy.wait(['@getUsers', '@getActivities', 'getComments']).then(function(xhrs){
|
||||
// xhrs will now be an array of matching XHR's
|
||||
// xhrs[0] <-- getUsers
|
||||
// xhrs[1] <-- getActivities
|
||||
// xhrs[2] <-- getComments
|
||||
})
|
||||
```
|
||||
|
||||
## You could also use the [`cy.spread`](https://on.cypress.io/api/spread) command here to spread the array into multiple arguments.
|
||||
**Using [`cy.spread()`](https://on.cypress.io/api/spread) to spread the array into multiple arguments.**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route(/users/).as("getUsers")
|
||||
.route(/activities/).as("getActivities")
|
||||
.route(/comments/).as("getComments")
|
||||
.wait(["@getUsers", "@getActivities", "getComments"])
|
||||
cy.server()
|
||||
cy.route('users/*').as('getUsers')
|
||||
cy.route('activities/*').as('getActivities')
|
||||
cy.route('comments/*').as('getComments')
|
||||
cy.wait(['@getUsers', '@getActivities', 'getComments'])
|
||||
.spread(function(getUsers, getActivities, getComments){
|
||||
// each XHR is now an individual argument
|
||||
})
|
||||
@@ -136,35 +200,33 @@ cy
|
||||
|
||||
# Notes
|
||||
|
||||
## requestTimeout and responseTimeout
|
||||
**requestTimeout and responseTimeout**
|
||||
|
||||
`cy.wait` goes through two separate "waiting" periods for a matching XHR.
|
||||
When used with an alias, `cy.wait()` goes through two separate "waiting" periods.
|
||||
|
||||
The first period waits for a matching request to leave the browser. This duration is configured by [`requestTimeout`](https://on.cypress.io/guides/configuration#timeouts) - which has a default of `5000` ms.
|
||||
|
||||
This means that when you begin waiting for an XHR, Cypress will wait up to 5 seconds for a matching XHR to be created. If no matching XHR is found, you will get an error message that looks like this:
|
||||
This means that when you begin waiting for an aliased XHR, Cypress will wait up to 5 seconds for a matching XHR to be created. If no matching XHR is found, you will get an error message that looks like this:
|
||||
|
||||

|
||||
|
||||
Once Cypress detects that a matching XHR has begun its request it then switches over to the 2nd waiting period. This duration is configured by [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) - which has a default of `20000` ms.
|
||||
Once Cypress detects that a matching XHR has begun its request, it then switches over to the 2nd waiting period. This duration is configured by [`responseTimeout`](https://on.cypress.io/guides/configuration#timeouts) - which has a default of `20000` ms.
|
||||
|
||||
This means Cypress will now wait up to 20 seconds for the external server to respond to this XHR. If no response is detected, you will get an error message that looks like this:
|
||||
|
||||

|
||||
|
||||
This gives you the best of both worlds - a fast error feedback loop when requests never go out, and a much longer duration for the actual external response.
|
||||
This gives you the best of both worlds - a fast error feedback loop when requests never go out and a much longer duration for the actual external response.
|
||||
|
||||
# Command Log
|
||||
|
||||
## Wait for the put to user to resolve.
|
||||
**Wait for the PUT to users to resolve.**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.server()
|
||||
.route("PUT", /users/, {}).as("userPut")
|
||||
.get("form").submit()
|
||||
.wait("@userPut")
|
||||
.its("url").should("include", "users")
|
||||
cy.server()
|
||||
cy.route('PUT', /users/, {}).as('userPut')
|
||||
cy.get('form').submit()
|
||||
cy.wait('@userPut').its('url').should('include', 'users')
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
@@ -175,9 +237,9 @@ When clicking on `wait` within the command log, the console outputs the followin
|
||||
|
||||
<img width="952" alt="screen shot 2015-11-29 at 2 21 11 pm" src="https://cloud.githubusercontent.com/assets/1271364/11459434/81132966-96a4-11e5-962f-41718b49b142.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [server](https://on.cypress.io/api/server)
|
||||
- [route](https://on.cypress.io/api/route)
|
||||
- [as](https://on.cypress.io/api/as)
|
||||
- [route](https://on.cypress.io/api/route)
|
||||
- [server](https://on.cypress.io/api/server)
|
||||
- [spread](https://on.cypress.io/api/spread)
|
||||
|
||||
@@ -4,51 +4,68 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Get the global `window` object of the remote application [visited](https://on.cypress.io/api/visit).
|
||||
Get the global `window` object of the remote application that was [visited](https://on.cypress.io/api/visit).
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the `window` object |
|
||||
| **Timeout** | `cy.window` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) |
|
||||
# Syntax
|
||||
|
||||
# [cy.window()](#usage)
|
||||
```javascript
|
||||
cy.window()
|
||||
cy.window(options)
|
||||
```
|
||||
|
||||
Get the global window object of the remote application you've visited.
|
||||
## Usage
|
||||
|
||||
# Options
|
||||
`cy.window()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.window`.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
**[cy.window( *options* )](#options-usage)**
|
||||
```javascript
|
||||
cy.window()
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.window()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Returns the remote window object
|
||||
`cy.window()` yields the `window` object.
|
||||
|
||||
## Timeout
|
||||
|
||||
`cy.window()` will retry for the duration of the [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts)
|
||||
|
||||
# Examples
|
||||
|
||||
## Window
|
||||
|
||||
**Returns the remote window object**
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.visit("http://localhost:8080/app")
|
||||
.window().then(function(win){
|
||||
// win is the remote window
|
||||
// of the page at: http://localhost:8080/app
|
||||
})
|
||||
cy.visit('http://localhost:8080/app')
|
||||
cy.window().then(function(win){
|
||||
// win is the remote window
|
||||
// of the page at: http://localhost:8080/app
|
||||
})
|
||||
```
|
||||
|
||||
# Options Usage
|
||||
## Options
|
||||
|
||||
## Passes timeout through to `cy.should` assertion
|
||||
**Passes timeout through to `cy.should` assertion**
|
||||
|
||||
```javascript
|
||||
cy.window({timeout: 10000}).should("have.property", "foo")
|
||||
cy.window({ timeout: 10000 }).should('have.property', 'foo')
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
## Get the window
|
||||
**Get the window**
|
||||
|
||||
```javascript
|
||||
cy.window()
|
||||
@@ -62,7 +79,7 @@ When clicking on `window` within the command log, the console outputs the follow
|
||||
|
||||
<img width="758" alt="screen shot 2015-11-29 at 2 16 22 pm" src="https://cloud.githubusercontent.com/assets/1271364/11459398/d0e6f4be-96a3-11e5-8583-69dcffef9cd3.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [visit](https://on.cypress.io/api/visit)
|
||||
- [document](https://on.cypress.io/api/document)
|
||||
|
||||
@@ -4,30 +4,56 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Reset the root scope to the current subject and pass that as an argument to the callback function.
|
||||
Set the scope of the containing commands to the previously yielded subject and pass that as an argument to the callback function.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the new DOM element(s) found by the command. |
|
||||
| **Timeout** | *cannot timeout* |
|
||||
|
||||
# [cy.within( *function* )](#usage)
|
||||
# Syntax
|
||||
|
||||
Set the root scope to the current subject
|
||||
```javascript
|
||||
.within(callbackFn)
|
||||
.within(options, callbackFn)
|
||||
```
|
||||
|
||||
# Options
|
||||
## Usage
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.within`.
|
||||
`.within()` requires being chained off another cy command that *yields* a DOM element.
|
||||
|
||||
**cy.within( *options*, *function* )**
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
cy.get('.list').within(function(list) {}) // Yield the `.list` and scope all commands within it
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.within(function() {}) // Errors, cannot be chained off 'cy'
|
||||
cy.getCookies().within(function() {}) // Errors, 'getCookies' does not yield DOM element
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} callbackFn** ***(Function)***
|
||||
|
||||
Pass a function that takes the current yielded subject as it's first argument.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.within()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `false` | Display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Get inputs within a form and submit the form
|
||||
## Timeout
|
||||
|
||||
# Examples
|
||||
|
||||
## Within
|
||||
|
||||
**Get inputs within a form and submit the form**
|
||||
|
||||
```html
|
||||
<form>
|
||||
@@ -38,14 +64,33 @@ Option | Default | Notes
|
||||
```
|
||||
|
||||
```javascript
|
||||
cy.get("form").within(function(){
|
||||
cy
|
||||
.get("input[name='email']").type("john.doe@email.com")
|
||||
.get("input[name='password']").type("password")
|
||||
.root().submit()
|
||||
cy.get('form').within(function(form){
|
||||
// cy.get() will only search for elements within form,
|
||||
// not within the entire document
|
||||
cy.get('input[name="email"]').type('john.doe@email.com')
|
||||
cy.get('input[name="password"]').type('password')
|
||||
cy.wrap(form).submit()
|
||||
})
|
||||
```
|
||||
|
||||
# Related
|
||||
# Command Log
|
||||
|
||||
**Get the input within the form**
|
||||
|
||||
```javascript
|
||||
cy.get('.query-form').within(function(el){
|
||||
cy.get('input:first')
|
||||
})
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
|
||||
<img width="461" alt="screen shot 2017-05-31 at 2 53 31 pm" src="https://cloud.githubusercontent.com/assets/1271364/26648611/05e133a0-4611-11e7-883e-735bc65cf739.png">
|
||||
|
||||
When clicking on the `within` command within the command log, the console outputs the following:
|
||||
|
||||
<img width="468" alt="screen shot 2017-05-31 at 2 53 49 pm" src="https://cloud.githubusercontent.com/assets/1271364/26648610/05d540fe-4611-11e7-9d20-d67c714beb6b.png">
|
||||
|
||||
# See also
|
||||
|
||||
- [root](https://on.cypress.io/api/root)
|
||||
|
||||
@@ -4,41 +4,80 @@ comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Return the object passed into `cy.wrap`.
|
||||
Yield the object passed into `.wrap()`.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the object passed into `cy.wrap` |
|
||||
| **Timeout** | *cannot timeout* |
|
||||
# Syntax
|
||||
|
||||
# [cy.wrap( *object* )](#usage)
|
||||
```javascript
|
||||
cy.wrap(subject)
|
||||
cy.wrap(subject, options)
|
||||
```
|
||||
|
||||
Return the object passed into `cy.wrap`.
|
||||
## Usage
|
||||
|
||||
# Options
|
||||
`cy.wrap()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.wrap`.
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
**cy.wrap( *object*, *options* )**
|
||||
```javascript
|
||||
cy.wrap({name: "Jane Lane"})
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} subject** ***(Object)***
|
||||
|
||||
An object to be yielded.
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.wrap()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`log` | `true` | whether to display command in command log
|
||||
|
||||
# Usage
|
||||
## Yields
|
||||
|
||||
## Invokes the function on the subject in wrap and returns the new value.
|
||||
`cy.wrap()` yields the object that was passed into the command.
|
||||
|
||||
## Timeout
|
||||
|
||||
# Examples
|
||||
|
||||
## Wrap
|
||||
|
||||
**Invokes the function on the subject in wrap and returns the new value.**
|
||||
|
||||
```javascript
|
||||
var fn = function(){
|
||||
return "bar"
|
||||
var getName = function() {
|
||||
return 'Jane Lane'
|
||||
}
|
||||
|
||||
cy.wrap({foo: fn}).invoke("foo").should("eq", "bar") // true
|
||||
cy.wrap({name: getName}).invoke('name').should('eq', 'Jane Lane') // true
|
||||
```
|
||||
|
||||
# Related
|
||||
# Command Log
|
||||
|
||||
**Make assertions about object**
|
||||
|
||||
```javascript
|
||||
cy.wrap({ amount: 10 })
|
||||
.should('have.property', 'amount')
|
||||
.and('eq', 10)
|
||||
```
|
||||
|
||||
The commands above will display in the command log as:
|
||||
|
||||
<img width="467" alt="screen shot 2017-05-31 at 3 16 58 pm" src="https://cloud.githubusercontent.com/assets/1271364/26649531/50ad5a32-4614-11e7-9733-9432d7e831b3.png">
|
||||
|
||||
When clicking on the `wrap` command within the command log, the console outputs the following:
|
||||
|
||||
<img width="404" alt="screen shot 2017-05-31 at 3 17 05 pm" src="https://cloud.githubusercontent.com/assets/1271364/26649532/50ad77e2-4614-11e7-83ab-9d9d37daefb7.png">
|
||||
|
||||
# See also
|
||||
|
||||
- [invoke](https://on.cypress.io/api/invoke)
|
||||
- [its](https://on.cypress.io/api/its)
|
||||
- [spread](https://on.cypress.io/api/spread)
|
||||
- [then](https://on.cypress.io/api/then)
|
||||
|
||||
@@ -1,99 +1,43 @@
|
||||
---
|
||||
---
|
||||
title: writefile
|
||||
comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Writes to a file with the specified contents. JavaScript arrays and objects are stringified and formatted into text. If the path to the file does not exist, the file and it's path will be created. If the file already exists, it will be over-written.
|
||||
Write to a file with the specified contents.
|
||||
|
||||
| | |
|
||||
|--- | --- |
|
||||
| **Returns** | the contents written to the file |
|
||||
| **Timeout** | `cy.writeFile` will wait for the duration of [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the server to write the file. |
|
||||
|
||||
# [cy.writeFile( *filePath*, *contents* )](#usage)
|
||||
|
||||
Writes to the `filePath` with the `contents`. The `filePath` is relative to the project's root. `contents` must be a string, an array, or an object.
|
||||
|
||||
# [cy.writeFile( *filePath*, *contents*, *encoding* )](#specify-encoding)
|
||||
|
||||
Writes to the `filePath` with the `contents` using the `encoding`. The `filePath` is relative to the project's root. `contents` must be a string, an array, or an object.
|
||||
|
||||
# Options
|
||||
|
||||
Pass in an options object to change the default behavior of `cy.writeFile`.
|
||||
|
||||
**[cy.writeFile( *filePath*, *contents*, *options* )](#options-usage)**
|
||||
|
||||
**[cy.writeFile( *filePath*, *contents*, *encoding*, *options* )](#options-usage)**
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the `cy.writeFile` command to be processed
|
||||
|
||||
# Usage
|
||||
|
||||
## Write some text to a `txt` file
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
// {projectRoot}/path/to/message.txt will be created with the contents "Hello World"
|
||||
cy
|
||||
.writeFile("path/to/message.txt", "Hello World")
|
||||
.then(function (text) {
|
||||
expect(text).to.equal("Hello World") // true
|
||||
})
|
||||
cy.writeFile(filePath, contents)
|
||||
cy.writeFile(filePath, contents, encoding)
|
||||
cy.writeFile(filePath, contents, options)
|
||||
cy.writeFile(filePath, contents, encoding, options)
|
||||
```
|
||||
|
||||
## Write JSON to a file
|
||||
## Usage
|
||||
|
||||
JavaScript arrays and objects are stringified and formatted into text.
|
||||
`cy.writeFile()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
// {projectRoot}/path/to/data.json will be created with the following:
|
||||
// {
|
||||
// "name": "Eliza",
|
||||
// "email": "eliza@example.com"
|
||||
// }
|
||||
|
||||
cy
|
||||
.writeFile("path/to/data.json", { name: "Eliza", email: "eliza@example.com" })
|
||||
.then(function (user) {
|
||||
// user will equal:
|
||||
// {
|
||||
// name: "Eliza",
|
||||
// email: "eliza@example.com"
|
||||
// }
|
||||
expect(user.name).to.equal("Eliza")
|
||||
})
|
||||
cy.writeFile('menu.json')
|
||||
```
|
||||
|
||||
## Write response data to a fixture file
|
||||
## Arguments
|
||||
|
||||
```javascript
|
||||
cy
|
||||
.request('https://jsonplaceholder.typicode.com/users')
|
||||
.then(function(response){
|
||||
cy.writeFile('cypress/fixtures/users.json', response.body)
|
||||
})
|
||||
// our fixture file is now generated and can be used
|
||||
.fixture('users')
|
||||
.then(function(users){
|
||||
expect(users[0].name).to.exist
|
||||
})
|
||||
```
|
||||
**{% fa fa-angle-right %} filePath** ***(String)***
|
||||
|
||||
## Specify encoding
|
||||
A path to a file within the project root (the directory that contains `cypress.json`).
|
||||
|
||||
Specify the encoding with the third argument.
|
||||
**{% fa fa-angle-right %} contents** ***(String, Array, or Object)***
|
||||
|
||||
```javascript
|
||||
// {projectRoot}/path/to/message.txt will be created with the contents "Hello World"
|
||||
// the encoding will be "ascii"
|
||||
cy.writeFile("path/to/ascii.txt", "Hello World", "ascii"))
|
||||
```
|
||||
The contents to be written to the file.
|
||||
|
||||
The following encodings are supported:
|
||||
**{% fa fa-angle-right %} encoding** ***(String)***
|
||||
|
||||
The encoding to be used when writing to the file. The following encodings are supported:
|
||||
|
||||
* `ascii`
|
||||
* `base64`
|
||||
@@ -107,12 +51,100 @@ The following encodings are supported:
|
||||
* `utf16le`
|
||||
* `utf-16le`
|
||||
|
||||
# Command Log
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
## Write an array to a file
|
||||
Pass in an options object to change the default behavior of `cy.writeFile()`.
|
||||
|
||||
Option | Default | Notes
|
||||
--- | --- | ---
|
||||
`timeout` | [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) | Total time to wait for the command to be processed.
|
||||
|
||||
## Yields
|
||||
|
||||
`cy.writeFile()` yields the contents written to the file.
|
||||
|
||||
## Timeout
|
||||
|
||||
`cy.writeFile()` will wait up for the duration of [`defaultCommandTimeout`](https://on.cypress.io/guides/configuration#timeouts) for the server to write to the file.
|
||||
|
||||
|
||||
# Examples
|
||||
|
||||
## Text
|
||||
|
||||
**Write some text to a `txt` file**
|
||||
|
||||
If the path to the file does not exist, the file and it's path will be created. If the file already exists, it will be over-written.
|
||||
|
||||
```javascript
|
||||
cy.writeFile("info.log", ["foo", "bar", "baz"])
|
||||
cy
|
||||
.writeFile('path/to/message.txt', 'Hello World')
|
||||
.then(function (text) {
|
||||
expect(text).to.equal('Hello World') // true
|
||||
})
|
||||
```
|
||||
|
||||
`{projectRoot}/path/to/message.txt` will be created with the following contents:
|
||||
|
||||
```text
|
||||
"Hello World"
|
||||
```
|
||||
|
||||
## JSON
|
||||
|
||||
**Write JSON to a file**
|
||||
|
||||
JavaScript arrays and objects are stringified and formatted into text.
|
||||
|
||||
```javascript
|
||||
cy.writeFile('path/to/data.json', { name: 'Eliza', email: 'eliza@example.com' })
|
||||
.then(function (user) {
|
||||
expect(user.name).to.equal('Eliza')
|
||||
})
|
||||
```
|
||||
|
||||
`{projectRoot}/path/to/data.json` will be created with the following contents:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Eliza",
|
||||
"email": "eliza@example.com"
|
||||
}
|
||||
```
|
||||
|
||||
**Write response data to a fixture file**
|
||||
|
||||
```javascript
|
||||
cy.request('https://jsonplaceholder.typicode.com/users').then(function(response){
|
||||
cy.writeFile('cypress/fixtures/users.json', response.body)
|
||||
})
|
||||
|
||||
// our fixture file is now generated and can be used
|
||||
cy.fixture('users').then(function(users){
|
||||
expect(users[0].name).to.exist
|
||||
})
|
||||
```
|
||||
|
||||
## Encoding
|
||||
|
||||
**Specify the encoding with the third argument.**
|
||||
|
||||
```javascript
|
||||
cy.writeFile('path/to/ascii.txt', 'Hello World', 'ascii'))
|
||||
```
|
||||
|
||||
`{projectRoot}/path/to/message.txt` will be created with the following contents:
|
||||
|
||||
```text
|
||||
Hello World
|
||||
```
|
||||
|
||||
# Command Log
|
||||
|
||||
**Write an array to a file**
|
||||
|
||||
```javascript
|
||||
cy.writeFile('info.log', ['foo', 'bar', 'baz'])
|
||||
```
|
||||
|
||||
The command above will display in the command log as:
|
||||
@@ -123,7 +155,7 @@ When clicking on the `writeFile` command within the command log, the console out
|
||||
|
||||
<img width="452" alt="screen shot of console output" src="https://cloud.githubusercontent.com/assets/1157043/17936161/df7e6bf8-69eb-11e6-8ef2-a90113dece9b.png">
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [readFile](https://on.cypress.io/api/readFile)
|
||||
- [Creating Fixtures](https://on.cypress.io/guides/creating-fixtures)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
title: commands
|
||||
---
|
||||
title: Cypress commands
|
||||
comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Cypress comes with its own API for creating custom commands. In fact, the same public methods *you* have access to are the same ones we use to create all of the built in commands. In other words, there's nothing special or different about ours versus yours. You can customize every aspect of commands, not only their behavior, but also their display in the Command Log.
|
||||
|
||||
@@ -1,45 +1,63 @@
|
||||
title: config
|
||||
---
|
||||
title: Cypress.config
|
||||
comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
`Cypress.config` allows you to `get` and `set` your configuration options.
|
||||
|
||||
This document covers the API for consuming your configuration options *in your tests*.
|
||||
`get` and `set` configuration options *in your tests*.
|
||||
|
||||
{% note info New to Cypress? %}
|
||||
[Read about configuration first.](https://on.cypress.io/guides/configuration)
|
||||
{% endnote %}
|
||||
|
||||
# [Cypress.config()](#section-no-arguments-usage)
|
||||
|
||||
Returns all of your configuration options as an object literal.
|
||||
|
||||
***
|
||||
|
||||
# [Cypress.config( *key* )](#section-key-usage)
|
||||
|
||||
Returns the value of a single configuration option by its key.
|
||||
|
||||
***
|
||||
|
||||
# [Cypress.config( *key*, *value* )](#section-key-value-usage)
|
||||
|
||||
Sets a configuration option for a specific key.
|
||||
|
||||
***
|
||||
|
||||
# [Cypress.config( *object* )](#section-object-usage)
|
||||
|
||||
Sets multiple configuration options.
|
||||
|
||||
***
|
||||
|
||||
# No Arguments Usage
|
||||
|
||||
## Get all configuration options.
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
// cypress.json
|
||||
Cypress.config()
|
||||
Cypress.config(name)
|
||||
Cypress.config(name, value)
|
||||
Cypress.config(object)
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`.config()` requires being chained off `Cypress`.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
Cypress.config() // Get configuration options
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.config() // Errors, cannot be chained off 'cy'
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} name** ***(String)***
|
||||
|
||||
The name of the configuration to get or set.
|
||||
|
||||
**{% fa fa-angle-right %} value** ***(String)***
|
||||
|
||||
The value of the configuration to set.
|
||||
|
||||
**{% fa fa-angle-right %} object** ***(Object)***
|
||||
|
||||
Set multiple configuration options with an object literal.
|
||||
|
||||
# Examples
|
||||
|
||||
## No Arguments
|
||||
|
||||
**Get all configuration options.**
|
||||
|
||||
***cypress.json***
|
||||
|
||||
```json
|
||||
{
|
||||
"defaultCommandTimeout": 10000
|
||||
}
|
||||
@@ -49,14 +67,13 @@ Sets multiple configuration options.
|
||||
Cypress.config() // => {defaultCommandTimeout: 10000, pageLoadTimeout: 30000, ...}
|
||||
```
|
||||
|
||||
***
|
||||
## Name
|
||||
|
||||
# Key Usage
|
||||
**Return just a single configuration option value.**
|
||||
|
||||
## Return just a single configuration option value.
|
||||
***cypress.json***
|
||||
|
||||
```javascript
|
||||
// cypress.json
|
||||
```json
|
||||
{
|
||||
"pageLoadTimeout": 60000
|
||||
}
|
||||
@@ -66,18 +83,17 @@ Cypress.config() // => {defaultCommandTimeout: 10000, pageLoadTimeout: 30000, ..
|
||||
Cypress.config("pageLoadTimeout") // => 60000
|
||||
```
|
||||
|
||||
***
|
||||
## Name and Value
|
||||
|
||||
# Key Value Usage
|
||||
**Cypress allows you to change the values of your configuration options from within your tests.**
|
||||
|
||||
## Cypress allows you to change the values of your configuration options from within your tests.
|
||||
|
||||
{% note warning %}
|
||||
{% note warning %}
|
||||
Any value you change will be permanently changed for the remainder of your tests.
|
||||
{% endnote %}
|
||||
|
||||
```javascript
|
||||
// cypress.json
|
||||
***cypress.json***
|
||||
|
||||
```json
|
||||
{
|
||||
"viewportWidth": 1280,
|
||||
"viewportHeight": 720
|
||||
@@ -90,18 +106,19 @@ Cypress.config("viewportWidth", 800)
|
||||
Cypress.config("viewportWidth") // => 800
|
||||
```
|
||||
|
||||
{% note info Using config to set baseUrl %}
|
||||
**Using config to set `baseUrl`**
|
||||
|
||||
{% note info %}
|
||||
[Check out our example recipe where we reset our baseUrl using Cypress.config](https://github.com/cypress-io/cypress-example-recipes/blob/master/cypress/integration/logging_in_single_sign_on_spec.js)
|
||||
{% endnote %}
|
||||
|
||||
***
|
||||
## Object
|
||||
|
||||
# Object Usage
|
||||
**You can set multiple values by passing an object literal.**
|
||||
|
||||
## You can set multiple values by passing an object literal.
|
||||
***cypress.json***
|
||||
|
||||
```javascript
|
||||
// cypress.json
|
||||
```json
|
||||
{
|
||||
"defaultCommandTimeout": 4000,
|
||||
"pageLoadTimeout": 30000,
|
||||
@@ -117,18 +134,14 @@ Cypress.config({
|
||||
Cypress.config() // => {defaultCommandTimeout: 10000, viewportHeight: 900, ...}
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
# Notes
|
||||
|
||||
## Why use `Cypress.config` instead of `cy.config`?
|
||||
**Why use `Cypress.config` instead of `cy.config`?**
|
||||
|
||||
As a rule of thumb anything you call from `Cypress` affects global state. Anything you call from `cy` affects local state.
|
||||
|
||||
Methods on `cy` are local and specific to a single test. Side effects from `cy` methods are restored between each test. We chose to use `Cypress` because changes to your configuration options take effect for the remainder of **ALL** tests.
|
||||
|
||||
***
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [Configuration](https://on.cypress.io/guides/configuration)
|
||||
|
||||
@@ -1,36 +1,65 @@
|
||||
title: cookies
|
||||
---
|
||||
title: Cypress.Cookies
|
||||
comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
`Cypress.Cookies` is a synchronous interface that allows you to do more than just get, set, or clear cookies.
|
||||
`Cookies.debug()`, `Cookies.preserveOnce()` and `Cookies.defaults()` allow you to do more than just get, set, or clear cookies.
|
||||
|
||||
Typically you'd use `Cypress.Cookies` in hooks like `before`, `beforeEach`, `after`, and `afterEach`.
|
||||
|
||||
Cypress automatically clears all cookies **before** each test to prevent state from building up. You can take advantage of `Cypress.Cookies.preserveOnce` or even **whitelist** cookies by their name to preserve values across multiple tests. This enables you to preserve sessions through several tests.
|
||||
Cypress automatically clears all cookies **before** each test to prevent state from building up.
|
||||
|
||||
# [Cypress.Cookies.debug( *boolean*, *options* )](#section-debug-usage)
|
||||
You can take advantage of `Cypress.Cookies.preserveOnce` or even *whitelist* cookies by their name to preserve values across multiple tests. This enables you to preserve sessions through several tests.
|
||||
|
||||
Enable or disable cookie debugging. When enabled, Cypress will log out when cookies are set or cleared.
|
||||
# Syntax
|
||||
|
||||
***
|
||||
```javascript
|
||||
Cypress.Cookies.debug(enable, options)
|
||||
Cypress.Cookies.preserveOnce(names...)
|
||||
Cypress.Cookies.defaults(options)
|
||||
```
|
||||
|
||||
# [Cypress.Cookies.preserveOnce( *name1*, *name2*, *name3*, ... )](#section-preserve-usage)
|
||||
## Usage
|
||||
|
||||
Will preserve cookies by name. Pass an unlimited number of arguments. These preserved cookies will not be cleared before the next test starts.
|
||||
`Cookies.debug()`, `Cookies.preserveOnce()` and `Cookies.defaults()` require being chained off `Cypress`.
|
||||
|
||||
***
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
# [Cypress.Cookies.defaults( *options* )](#section-defaults-usage)
|
||||
```javascript
|
||||
Cypress.Cookies.debug()
|
||||
Cypress.Cookies.preserveOnce('appId')
|
||||
Cypress.Cookies.defaults()
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.Cookies.debug() // Errors, cannot be chained off 'cy'
|
||||
```
|
||||
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} enable** ***(Boolean)***
|
||||
|
||||
Whether cookie debugging should be enabled.
|
||||
|
||||
**{% fa fa-angle-right %} names**
|
||||
|
||||
Names of cookies to be preserved. Pass an unlimited number of arguments.
|
||||
|
||||
**{% fa fa-angle-right %} object** ***(Object)***
|
||||
|
||||
Set defaults for all cookies, such as whitelisting a set of cookies to bypass being cleared before each test.
|
||||
|
||||
***
|
||||
# Examples
|
||||
|
||||
# Debug Usage
|
||||
## Debug
|
||||
|
||||
## Log out when cookie values set or clear
|
||||
**Log out when cookie values set or clear**
|
||||
|
||||
By turning on debugging, Cypress will automatically log out to the console when it **sets** or **clears** cookie values. This is useful to help you understand how Cypress clears cookies before each test, and is useful to visualize how to handle preserving cookies in between tests.
|
||||
By turning on debugging, Cypress will automatically log out to the console when it *sets* or *clears* cookie values. This is useful to help you understand how Cypress clears cookies before each test, and is useful to visualize how to handle preserving cookies in between tests.
|
||||
|
||||
```javascript
|
||||
Cypress.Cookies.debug(true) // now Cypress will log out when it alters cookies
|
||||
@@ -41,7 +70,7 @@ cy.setCookie('foo', 'bar')
|
||||
|
||||

|
||||
|
||||
## Turn off verbose debugging output
|
||||
**Turn off verbose debugging output**
|
||||
|
||||
By default Cypress will log out the cookie object which allows you to inspect all of its properties. However you may not need that level of detail and you can turn this off.
|
||||
|
||||
@@ -53,27 +82,25 @@ Now when Cypress logs cookies they will only include the `name` and `value`.
|
||||
|
||||

|
||||
|
||||
Debugging will be turned on until you explictly turn it back off.
|
||||
Debugging will be turned on until you explicitly turn it off.
|
||||
|
||||
```javascript
|
||||
Cypress.Cookies.debug(false) // now debugging is turned off
|
||||
```
|
||||
|
||||
***
|
||||
## Preserve Once
|
||||
|
||||
# Preserve Usage
|
||||
|
||||
## Preserve cookies through multiple tests
|
||||
**Preserve cookies through multiple tests**
|
||||
|
||||
Cypress gives you a simple interface to automatically preserve cookies for multiple tests. Cypress automatically clears all cookies before each new test starts by default.
|
||||
|
||||
By clearing cookies before each test you are gauranteed to always start from a clean slate. Starting from a clean state prevents coupling your tests to one another and prevents situations where mutating something in your application in one test affects another one downstream.
|
||||
By clearing cookies before each test you are guaranteed to always start from a clean slate. Starting from a clean state prevents coupling your tests to one another and prevents situations where mutating something in your application in one test affects another one downstream.
|
||||
|
||||
{% note info %}
|
||||
The most common use case for preserving cookies is to prevent having to log in to your application before each individual test. This is a problem if the majority of each test is spent logging in a user.
|
||||
{% endnote %}
|
||||
|
||||
You can use `Cypress.Cookies.preserveOnce` to preserve cookies through multiple tests.
|
||||
You can use `Cypress.Cookies.preserveOnce()` to preserve cookies through multiple tests.
|
||||
|
||||
There are *likely* better ways to do this, but this isn't well documented at the moment. Every application is different and there is no one-size-fits-all solution. For the moment, if you're using session-based cookies, this method will work.
|
||||
|
||||
@@ -111,11 +138,9 @@ describe("Dashboard", function(){
|
||||
})
|
||||
```
|
||||
|
||||
***
|
||||
## Defaults
|
||||
|
||||
# Defaults Usage
|
||||
|
||||
## Set global default cookies
|
||||
**Set global default cookies**
|
||||
|
||||
You can modify the global defaults and whitelist a set of Cookies which will always be preserved across tests.
|
||||
|
||||
@@ -127,14 +152,14 @@ A great place to put this configuration is in your `cypress/support/defaults.js`
|
||||
|
||||
**Whitelist accepts:**
|
||||
|
||||
- string
|
||||
- array
|
||||
- regexp
|
||||
- function
|
||||
- String
|
||||
- Array
|
||||
- RegExp
|
||||
- Function
|
||||
|
||||
***Whitelist String***
|
||||
|
||||
```javascript
|
||||
// string usage
|
||||
|
||||
// now any cookie with the name 'session_id' will
|
||||
// not be cleared before each test runs
|
||||
Cypress.Cookies.defaults({
|
||||
@@ -142,9 +167,9 @@ Cypress.Cookies.defaults({
|
||||
})
|
||||
```
|
||||
|
||||
```javascript
|
||||
// array usage
|
||||
***Whitelist Array***
|
||||
|
||||
```javascript
|
||||
// now any cookie with the name 'session_id' or 'remember_token'
|
||||
// will not be cleared before each test runs
|
||||
Cypress.Cookies.defaults({
|
||||
@@ -152,9 +177,9 @@ Cypress.Cookies.defaults({
|
||||
})
|
||||
```
|
||||
|
||||
```javascript
|
||||
// RegExp usage
|
||||
***Whitelist RegExp***
|
||||
|
||||
```javascript
|
||||
// now any cookie that matches this RegExp
|
||||
// will not be cleared before each test runs
|
||||
Cypress.Cookies.defaults({
|
||||
@@ -162,9 +187,9 @@ Cypress.Cookies.defaults({
|
||||
})
|
||||
```
|
||||
|
||||
```javascript
|
||||
// function usage
|
||||
***Whitelist Function***
|
||||
|
||||
```javascript
|
||||
Cypress.Cookies.defaults({
|
||||
whitelist: function(cookie){
|
||||
// implement your own logic here
|
||||
@@ -175,9 +200,7 @@ Cypress.Cookies.defaults({
|
||||
})
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
# Related
|
||||
# See also
|
||||
|
||||
- [clearCookie](https://on.cypress.io/api/clearcookie)
|
||||
- [clearCookies](https://on.cypress.io/api/clearcookies)
|
||||
|
||||
@@ -1,23 +1,43 @@
|
||||
title: dom
|
||||
---
|
||||
title: Cypress.Dom
|
||||
comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
`Cypress.Dom` holds methods and logic related to DOM.
|
||||
`Cypress.Dom.isHidden()` allows you to work with logic that determines whether an element is hidden.
|
||||
|
||||
# [Cypress.Dom.isHidden( *element* )](#section-is-hidden-usage)
|
||||
# Syntax
|
||||
|
||||
Returns a boolean indicating whether an element is hidden.
|
||||
```javascript
|
||||
Cypress.Dom.isHidden(element)
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`Dom.isHidden()` requires being chained off `Cypress`.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
Cypress.Dom.isHidden('form')
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.Dom.isHidden('form') // Errors, cannot be chained off 'cy'
|
||||
```
|
||||
|
||||
# Examples
|
||||
|
||||
## Is Hidden
|
||||
|
||||
**Returns a boolean indicating whether an element is hidden.**
|
||||
|
||||
Cypress internally uses this method *everywhere* to figure out whether an element is hidden.
|
||||
|
||||
***
|
||||
|
||||
# Is Hidden Usage
|
||||
|
||||
```javascript
|
||||
var $el = $("#modal")
|
||||
|
||||
Cypress.Dom.isHidden($el) // => false
|
||||
|
||||
```
|
||||
|
||||
|
||||
@@ -1,45 +1,63 @@
|
||||
title: env
|
||||
---
|
||||
title: Cypress.env
|
||||
comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
`Cypress.env` allows you to `get` and `set` your environment variables.
|
||||
`get` and `set` environment variables *in your tests*.
|
||||
|
||||
This document covers the API for consuming your environment variables *in your tests*. The [Environment Variable](https://on.cypress.io/guides/environment-variables) guide explains the 4 ways you can set them *outside of your tests*.
|
||||
|
||||
{% note info New to Cypress? %}
|
||||
[Read about environment variables first.](https://on.cypress.io/guides/environment-variables)
|
||||
{% note info %}
|
||||
The [Environment Variable](https://on.cypress.io/guides/environment-variables) guide explains the 4 ways you can set them *outside of your tests*.
|
||||
{% endnote %}
|
||||
|
||||
# [Cypress.env()](#section-no-arguments-usage)
|
||||
|
||||
Returns all of your environment variables as an object literal.
|
||||
|
||||
***
|
||||
|
||||
# [Cypress.env( *key* )](#section-key-usage)
|
||||
|
||||
Returns the value of a single environment variable by its key.
|
||||
|
||||
***
|
||||
|
||||
# [Cypress.env( *key*, *value* )](#section-key-value-usage)
|
||||
|
||||
Sets an environment variable for a specific key.
|
||||
|
||||
***
|
||||
|
||||
# [Cypress.env( *object* )](#section-object-usage)
|
||||
|
||||
Sets multiple environment variables.
|
||||
|
||||
***
|
||||
|
||||
# No Arguments Usage
|
||||
|
||||
## Get all environment variables.
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
// cypress.json
|
||||
Cypress.env()
|
||||
Cypress.env(name)
|
||||
Cypress.env(name, value)
|
||||
Cypress.env(object)
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`.env()` requires being chained off `Cypress`.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
Cypress.env() // Get environment variables
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.env() // Errors, cannot be chained off 'cy'
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} name** ***(String)***
|
||||
|
||||
The name of the environment variable to get or set.
|
||||
|
||||
**{% fa fa-angle-right %} value** ***(String)***
|
||||
|
||||
The value of the environment variable to set.
|
||||
|
||||
**{% fa fa-angle-right %} object** ***(Object)***
|
||||
|
||||
Set multiple environment variables with an object literal.
|
||||
|
||||
# Examples
|
||||
|
||||
## No Arguments
|
||||
|
||||
**Get all environment variables.**
|
||||
|
||||
***cypress.json***
|
||||
|
||||
```json
|
||||
{
|
||||
"env": {
|
||||
"foo": "bar",
|
||||
@@ -52,14 +70,13 @@ Sets multiple environment variables.
|
||||
Cypress.env() // => {foo: "bar", baz: "quux"}
|
||||
```
|
||||
|
||||
***
|
||||
## Name
|
||||
|
||||
# Key Usage
|
||||
**Return just a single environment variable value.**
|
||||
|
||||
## Return just a single environment variable value.
|
||||
***cypress.json***
|
||||
|
||||
```javascript
|
||||
// cypress.json
|
||||
```json
|
||||
{
|
||||
"env": {
|
||||
"foo": "bar",
|
||||
@@ -73,18 +90,17 @@ Cypress.env("foo") // => bar
|
||||
Cypress.env("baz") // => quux
|
||||
```
|
||||
|
||||
***
|
||||
# Name and Value
|
||||
|
||||
# Key Value Usage
|
||||
|
||||
## Cypress allows you to change the values of your environment variables from within your tests.
|
||||
**Cypress allows you to change the values of your environment variables from within your tests.**
|
||||
|
||||
{% note warning %}
|
||||
Any value you change will be permanently changed for the remainder of your tests.
|
||||
{% endnote %}
|
||||
|
||||
```javascript
|
||||
// cypress.json
|
||||
***cypress.json***
|
||||
|
||||
```json
|
||||
{
|
||||
"env": {
|
||||
"foo": "bar",
|
||||
@@ -99,14 +115,13 @@ Cypress.env("host", "http://server.dev.local")
|
||||
Cypress.env("host") // => http://server.dev.local
|
||||
```
|
||||
|
||||
***
|
||||
## Object
|
||||
|
||||
# Object Usage
|
||||
**You can set multiple values by passing an object literal.**
|
||||
|
||||
## You can set multiple values by passing an object literal.
|
||||
***cypress.json***
|
||||
|
||||
```javascript
|
||||
// cypress.json
|
||||
```json
|
||||
{
|
||||
"env": {
|
||||
"foo": "bar",
|
||||
@@ -124,25 +139,19 @@ Cypress.env({
|
||||
Cypress.env() // => {foo: "foo", baz: "quux", host: "http://server.dev.local"}
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
# Notes
|
||||
|
||||
## Why use `Cypress.env` instead of `cy.env`?
|
||||
**Why use `Cypress.env` instead of `cy.env`?**
|
||||
|
||||
As a rule of thumb anything you call from `Cypress` affects global state. Anything you call from `cy` affects local state.
|
||||
|
||||
Methods on `cy` are local and specific to a single test. Side effects from `cy` methods are restored between each test. We chose to use `Cypress` because changes to your environment variables take effect for the remainder of **ALL** tests.
|
||||
|
||||
***
|
||||
|
||||
## Why would I ever need to use environment variables?
|
||||
**Why would I ever need to use environment variables?**
|
||||
|
||||
The [Environment Variables](https://on.cypress.io/guides/environment-variables) guide explains common use cases.
|
||||
|
||||
***
|
||||
|
||||
## Can I pass in environment variables from the command line?
|
||||
**Can I pass in environment variables from the command line?**
|
||||
|
||||
Yes. You can do that and much more.
|
||||
|
||||
|
||||
@@ -1,26 +1,51 @@
|
||||
title: api-server
|
||||
---
|
||||
title: Cypress.Server
|
||||
comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Any configuration you pass to [`cy.server`](https://on.cypress.io/api/server) will only persist until the end of the test. If you find yourself passing the same configuration to each [`cy.server`](https://on.cypress.io/api/server), then you might want to permanently change the default options for all [`cy.server`](https://on.cypress.io/api/server) instances.
|
||||
Permanently change the default options for all [`cy.server()`](https://on.cypress.io/api/server) instances
|
||||
|
||||
***
|
||||
|
||||
# [Cypress.Server.defaults( *object* )](#section-usage)
|
||||
|
||||
Change default configuration for [`cy.server`](https://on.cypress.io/api/server)
|
||||
|
||||
{% note info %}
|
||||
A great place to put this configuration is in your `cypress/support/defaults.js` file, since it is loaded before any test files are evaluated.
|
||||
{% note info New to Cypress? %}
|
||||
Any configuration you pass to [`cy.server()`](https://on.cypress.io/api/server) will only persist until the end of the test.
|
||||
{% endnote %}
|
||||
|
||||
***
|
||||
|
||||
# Usage
|
||||
# Syntax
|
||||
|
||||
```javascript
|
||||
// pass anything here you'd normally pass
|
||||
// to cy.server(). These options will be the new defaults.
|
||||
Cypress.Server.defaults(options)
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`Server.defaults()` requires being chained off `Cypress`.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
Cypress.Server.defaults({}) // Set server defaults
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.Server.defaults({}) // Errors, cannot be chained off 'cy'
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
**{% fa fa-angle-right %} options** ***(Object)***
|
||||
|
||||
Pass in an options object to change the default behavior of `.filter()`.
|
||||
|
||||
# Examples
|
||||
|
||||
## Options
|
||||
|
||||
**These options will be the new defaults.**
|
||||
|
||||
```javascript
|
||||
// pass anything here you'd normally pass to cy.server().
|
||||
Cypress.Server.defaults({
|
||||
delay: 500,
|
||||
force404: false,
|
||||
@@ -28,4 +53,14 @@ Cypress.Server.defaults({
|
||||
// handle custom logic for whitelisting
|
||||
}
|
||||
})
|
||||
```
|
||||
```
|
||||
|
||||
# Notes
|
||||
|
||||
**Where to put server configuration**
|
||||
|
||||
A great place to put this configuration is in your `cypress/support/defaults.js` file, since it is loaded before any test files are evaluated.
|
||||
|
||||
# See also
|
||||
|
||||
- [server](https://on.cypress.io/api/server)
|
||||
|
||||
@@ -1,41 +1,55 @@
|
||||
title: cypress-jquery
|
||||
comments: true
|
||||
---
|
||||
|
||||
# [Cypress.$( **selector** )](#section-selector-usage)
|
||||
title: Cypress.$
|
||||
comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Cypress automatically proxies [jQuery](https://jquery.com/) and exposes it as `Cypress.$`
|
||||
|
||||
Calling `Cypress.$("button")` will automatically query for elements in your `remote window`. In other words, Cypress automatically sets the `document` to be whatever you've currently navigated to via [`cy.visit`](https://on.cypress.io/api/visit).
|
||||
Calling `Cypress.$('button')` will automatically query for elements in your remote `window`. In other words, Cypress automatically sets the `document` to be whatever you've currently navigated to via [`cy.visit()`](https://on.cypress.io/api/visit).
|
||||
|
||||
This is a great way to *synchronously* query for elements when debugging from Chrome Dev Tools.
|
||||
This is a great way to *synchronously* query for elements when debugging from Developer Tools.
|
||||
|
||||
***
|
||||
# Syntax
|
||||
|
||||
# Other proxied jQuery methods
|
||||
```javascript
|
||||
Cypress.$(selector)
|
||||
|
||||
* `Cypress.$.Event`
|
||||
* `Cypress.$.Deferred`
|
||||
* `Cypress.$.ajax`
|
||||
* `Cypress.$.get`
|
||||
* `Cypress.$.getJSON`
|
||||
* `Cypress.$.getScript`
|
||||
* `Cypress.$.post`
|
||||
// other proxied jQuery methods
|
||||
Cypress.$.Event
|
||||
Cypress.$.Deferred
|
||||
Cypress.$.ajax
|
||||
Cypress.$.get
|
||||
Cypress.$.getJSON
|
||||
Cypress.$.getScript
|
||||
Cypress.$.post
|
||||
```
|
||||
|
||||
{% note info %}
|
||||
If you're looking to make an XHR request in your test scripts, use [`cy.request`](https://on.cypress.io/api/request)
|
||||
{% endnote %}
|
||||
## Usage
|
||||
|
||||
***
|
||||
`.config()` requires being chained off `Cypress`.
|
||||
|
||||
# Selector Usage
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
Cypress.$('p')
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.$('p') // Errors, cannot be chained off 'cy'
|
||||
```
|
||||
|
||||
# Examples
|
||||
|
||||
## Selector
|
||||
|
||||
```javascript
|
||||
var $li = Cypress.$("ul li:first")
|
||||
|
||||
cy
|
||||
.wrap($li)
|
||||
.should("not.have.class", "active")
|
||||
cy.wrap($li)
|
||||
.should("not.have.class", "active")
|
||||
.click()
|
||||
.should("have.class", "active")
|
||||
```
|
||||
.should("have.class", "active")
|
||||
```
|
||||
|
||||
@@ -1,18 +1,36 @@
|
||||
title: cypress-underscore
|
||||
---
|
||||
title: Cypress._
|
||||
comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
# [Cypress._.method()](#section-usage)
|
||||
Cypress automatically proxies [Underscore](http://underscorejs.org/) and exposes it as `Cypress._`. Call any valid Underscore method on `Cypress._`
|
||||
|
||||
Cypress automatically proxies [Underscore](http://underscorejs.org/) and exposes it as `Cypress._`
|
||||
# Syntax
|
||||
|
||||
Call any valid Underscore method with `Cypress._`
|
||||
```javascript
|
||||
Cypress._.method()
|
||||
```
|
||||
|
||||
***
|
||||
## Usage
|
||||
|
||||
# Usage
|
||||
`._.method()` requires being chained off `Cypress`.
|
||||
|
||||
## Use _.each
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
Cypress._.keys(obj)
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy._.keys(obj) // Errors, cannot be chained off 'cy'
|
||||
```
|
||||
|
||||
# Examples
|
||||
|
||||
## `_.each`
|
||||
|
||||
```javascript
|
||||
// set local reference to underscore
|
||||
@@ -29,7 +47,7 @@ cy.get("li").then(function($li){
|
||||
})
|
||||
```
|
||||
|
||||
## Chain underscore methods
|
||||
## `_.chain`
|
||||
|
||||
```javascript
|
||||
cy
|
||||
@@ -40,4 +58,4 @@ cy
|
||||
|
||||
expect(ids).to.deep.eq([1, 2, 3])
|
||||
})
|
||||
```
|
||||
```
|
||||
|
||||
@@ -1,48 +1,69 @@
|
||||
title: cypress-blob
|
||||
comments: true
|
||||
---
|
||||
|
||||
# [Cypress.Blob.method()](#setion-usage)
|
||||
title: Cypress.Blob
|
||||
comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Cypress proxies a [`Blob Utilities`](https://github.com/nolanlawson/blob-util) library and exposes it as `Cypress.Blob`.
|
||||
|
||||
Use `Cypress.Blob` to convert `base64` strings to `blob` objects. Useful for testing uploads.
|
||||
|
||||
***
|
||||
# Syntax
|
||||
|
||||
# Usage
|
||||
```javascript
|
||||
Cypress.Blob.method()
|
||||
```
|
||||
|
||||
## Using an image fixture
|
||||
## Usage
|
||||
|
||||
`.Blob.method()` requires being chained off `Cypress`.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
Cypress.Blob.method()
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.Blob.method() // Errors, cannot be chained off 'cy'
|
||||
```
|
||||
|
||||
# Examples
|
||||
|
||||
## Image Fixture
|
||||
|
||||
**Using an image fixture**
|
||||
|
||||
```javascript
|
||||
// programmatically upload the logo
|
||||
cy
|
||||
.fixture("images/logo.png").as("logo")
|
||||
.get("input[type=file]").then(function($input){
|
||||
cy.fixture("images/logo.png").as("logo")
|
||||
cy.get("input[type=file]").then(function($input){
|
||||
|
||||
// convert the logo base64 string to a blob
|
||||
return Cypress.Blob.base64StringToBlob(this.logo, "image/png").then(function(blob){
|
||||
// convert the logo base64 string to a blob
|
||||
return Cypress.Blob.base64StringToBlob(this.logo, "image/png").then(function(blob){
|
||||
|
||||
// pass the blob to the fileupload jQuery plugin
|
||||
// which initiates a programmatic upload
|
||||
$input.fileupload("add", {files: blob})
|
||||
})
|
||||
// pass the blob to the fileupload jQuery plugin
|
||||
// used in your application's code
|
||||
// which initiates a programmatic upload
|
||||
$input.fileupload("add", {files: blob})
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Getting dataUrl string
|
||||
|
||||
**create an `img` element and set its `src` to the `dataUrl`**
|
||||
|
||||
```javascript
|
||||
return Cypress.Blob.imgSrcToDataURL("/assets/img/logo.png").then(function(dataUrl){
|
||||
|
||||
// create an <img> element and set its src to the dataUrl
|
||||
var img = Cypress.$("<img />", {src: dataUrl})
|
||||
|
||||
cy
|
||||
.get(".utility-blob").then(function($div){
|
||||
// append the image
|
||||
$div.append(img)
|
||||
})
|
||||
.get(".utility-blob img").click().should("have.attr", "src", dataUrl)
|
||||
cy.get(".utility-blob").then(function($div){
|
||||
// append the image
|
||||
$div.append(img)
|
||||
})
|
||||
cy.get(".utility-blob img").click().should("have.attr", "src", dataUrl)
|
||||
})
|
||||
```
|
||||
|
||||
@@ -1,22 +1,40 @@
|
||||
title: cypress-minimatch
|
||||
comments: true
|
||||
---
|
||||
|
||||
# [Cypress.minimatch()](#section-usage)
|
||||
title: Cypress.minimatch
|
||||
comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Cypress automatically proxies [`minimatch`](https://github.com/isaacs/minimatch) and exposes it as `Cypress.minimatch`.
|
||||
|
||||
Use `Cypress.minimatch` to test out glob patterns against strings.
|
||||
|
||||
***
|
||||
# Syntax
|
||||
|
||||
# Usage
|
||||
```javascript
|
||||
Cypress.minimatch()
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`.minimatch()` requires being chained off `Cypress`.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
Cypress.minimatch()
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.minimatch() // Errors, cannot be chained off 'cy'
|
||||
```
|
||||
|
||||
# Examples
|
||||
|
||||
By default Cypress uses `minimatch` to test glob patterns against XHR URLs.
|
||||
|
||||
If you're struggling with writing the correct pattern you can iterate much faster by testing directly in your Chrome Dev Tools console.
|
||||
|
||||
Pop open that baby and write the following:
|
||||
If you're struggling with writing the correct pattern you can iterate much faster by testing directly in your Developer Tools console.
|
||||
|
||||
```javascript
|
||||
// test that the glob you're writing matches the XHR's url
|
||||
@@ -50,4 +68,4 @@ Cypress.minimatch("/foo/bar/baz/123/quux?a=b&c=2", "/foo/**", {
|
||||
Cypress.minimatch("/foo/bar/baz/123/quux?a=b&c=2", "/foo/*", {
|
||||
matchBase: false
|
||||
})
|
||||
```
|
||||
```
|
||||
|
||||
@@ -1,20 +1,41 @@
|
||||
title: cypress-moment
|
||||
comments: true
|
||||
---
|
||||
|
||||
# [Cypress.moment()](#section-usage)
|
||||
title: Cypress.moment
|
||||
comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Cypress automatically proxies [`moment.js`](http://momentjs.com/) and exposes it as `Cypress.moment`.
|
||||
|
||||
Use `Cypress.moment` to help format or parse dates.
|
||||
|
||||
***
|
||||
# Syntax
|
||||
|
||||
# Usage
|
||||
```javascript
|
||||
Cypress.moment()
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`.moment()` requires being chained off `Cypress`.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
Cypress.moment()
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
cy.moment() // Errors, cannot be chained off 'cy'
|
||||
```
|
||||
|
||||
# Examples
|
||||
|
||||
**test that the span contains formatted text for today**
|
||||
|
||||
```javascript
|
||||
var todaysDate = Cypress.moment().format("MMM DD, YYYY")
|
||||
|
||||
// test that the span contains formatted text for today
|
||||
cy.get("span").should("contain", "Order shipped on: " + todaysDate)
|
||||
```
|
||||
```
|
||||
|
||||
@@ -1,16 +1,36 @@
|
||||
title: cypress-promise
|
||||
comments: true
|
||||
---
|
||||
|
||||
# [new Cypress.Promise( *function* )](#section-usage)
|
||||
title: Cypress.Promise
|
||||
comments: true
|
||||
description: ''
|
||||
---
|
||||
|
||||
Cypress automatically proxies [`Bluebird`](https://github.com/petkaantonov/bluebird) and exposes it as `Cypress.Promise`.
|
||||
|
||||
Instantiate a new bluebird promise.
|
||||
|
||||
***
|
||||
# Syntax
|
||||
|
||||
# Usage
|
||||
```javascript
|
||||
new Cypress.Promise(fn)
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`.Promise` requires being chained off `Cypress`.
|
||||
|
||||
**{% fa fa-check-circle green %} Valid Usage**
|
||||
|
||||
```javascript
|
||||
new Cypress.Promise
|
||||
```
|
||||
|
||||
**{% fa fa-exclamation-triangle red %} Invalid Usage**
|
||||
|
||||
```javascript
|
||||
new cy.Promise // Errors, cannot be chained off 'cy'
|
||||
```
|
||||
|
||||
# Examples
|
||||
|
||||
Use `Cypress.Promise` to create promises. Cypress is promise aware so if you return a promise from inside of commands like [`cy.then`](https://on.cypress.io/api/then), Cypress will not continue until those promises resolve.
|
||||
|
||||
@@ -24,8 +44,6 @@ cy.get("button").then(function($button){
|
||||
})
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
## Waiting for Promises
|
||||
|
||||
```javascript
|
||||
@@ -45,14 +63,13 @@ it("waits for promises to resolve", function(){
|
||||
})
|
||||
}
|
||||
|
||||
cy
|
||||
.then(function(){
|
||||
// return a promise to cy.then() that
|
||||
// is awaited until it resolves
|
||||
return waitOneSecond().then(function(str){
|
||||
expect(str).to.eq('foo')
|
||||
expect(waited).to.be.true
|
||||
})
|
||||
cy.then(function(){
|
||||
// return a promise to cy.then() that
|
||||
// is awaited until it resolves
|
||||
return waitOneSecond().then(function(str){
|
||||
expect(str).to.eq('foo')
|
||||
expect(waited).to.be.true
|
||||
})
|
||||
})
|
||||
})
|
||||
```
|
||||
```
|
||||
|
||||
494
docs/source/guides-old/references/error-messages.md
Normal file
494
docs/source/guides-old/references/error-messages.md
Normal file
@@ -0,0 +1,494 @@
|
||||
title: errors
|
||||
comments: true
|
||||
---
|
||||
|
||||
# No tests found in your file
|
||||
|
||||

|
||||
|
||||
This message means that Cypress was unable to find tests in the specified file. You'll likely get this message if you have an empty test file and have not yet written any tests.
|
||||
|
||||
***
|
||||
|
||||
# We found an error preparing your test file
|
||||
|
||||
This message means that Cypress encountered an error when compiling and/or bundling your test file.
|
||||
|
||||
Cypress automatically compiles and bundles your test code so you can use ES2015, CoffeeScript, modules, etc.
|
||||
|
||||
You'll typically receive this message due to:
|
||||
|
||||
- The file missing
|
||||
- A syntax error in the file or one of its dependencies
|
||||
- A missing dependency
|
||||
|
||||
The error will be printed on the right side, usually showing the part of the code in which the error occurred.
|
||||
|
||||
When you fix the error in your code, your tests will automatically re-run.
|
||||
|
||||
***
|
||||
|
||||
# Cypress cannot execute commands outside a running test
|
||||
|
||||

|
||||
|
||||
This message means you tried to execute one or more Cypress commands outside of a currently running test. Cypress has to be able to associate commands to a specific test.
|
||||
|
||||
Typically this happens accidentally, like in the following situation.
|
||||
|
||||
```javascript
|
||||
describe("Some Tests", function(){
|
||||
it("is true", function(){
|
||||
expect(true).to.be.true // yup, fine
|
||||
})
|
||||
|
||||
it("is false", function(){
|
||||
expect(false).to.be.false // yup, also fine
|
||||
})
|
||||
|
||||
context("some nested tests", function(){
|
||||
// oops you forgot to write an it(...) here!
|
||||
// these cypress commands below
|
||||
// are run outside of a test and cypress
|
||||
// throws an error
|
||||
cy
|
||||
.visit("http://localhost:8080")
|
||||
.get("h1").should("contain", "todos")
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
Simply move those Cypress commands into an `it(...)` and everything will work correctly.
|
||||
|
||||
If you are purposefully writing commands outside of a test, there is probably a better way to accomplish whatever you're trying to do. Read through the [Example Repos](https://on.cypress.io/guides/all-example-apps), [open an issue](https://github.com/cypress-io/cypress/issues/new), or [come talk to someone in Gitter](https://gitter.im/cypress-io/cypress).
|
||||
|
||||
***
|
||||
|
||||
# cy.method() failed because the element you are chaining off of has become detached or removed from the dom
|
||||
|
||||

|
||||
|
||||
This message means you are trying to interact with a "dead" DOM element - meaning it is either detached or completely removed from the DOM.
|
||||
|
||||
Cypress errors because it cannot operate or interact with "dead" elements - just like a real user could not do this either.
|
||||
|
||||
Understanding how this happens is very important - and it is often easy to prevent. Let's investigate.
|
||||
|
||||
```html
|
||||
<!-- your app HTML -->
|
||||
<body>
|
||||
<div id="parent">
|
||||
<button>delete</button>
|
||||
</div>
|
||||
</body>
|
||||
```
|
||||
|
||||
```javascript
|
||||
// your app code
|
||||
$("button").click(function(){
|
||||
// when the <button> is clicked
|
||||
// we remove the button from the DOM
|
||||
$(this).remove()
|
||||
})
|
||||
```
|
||||
|
||||
```javascript
|
||||
// buggy test code
|
||||
cy
|
||||
// as soon as this click event happens the <button>
|
||||
// becomes removed from the DOM
|
||||
.get("button").click()
|
||||
|
||||
// When cypress begins processing the 'parent' command
|
||||
// it will immediately detect that the current subject
|
||||
// which is the <button> is detached from the DOM and
|
||||
// will throw the error
|
||||
.parent()
|
||||
```
|
||||
|
||||
We can prevent Cypress from throwing this error by rewriting our test code:
|
||||
|
||||
```javascript
|
||||
// fixed test code
|
||||
cy
|
||||
.get("button").click()
|
||||
|
||||
// simply query for the parent directly here
|
||||
// instead of chaining off the <button> subject
|
||||
.get("#parent")
|
||||
```
|
||||
|
||||
The above example is an oversimplification. Let's look at a more complex example.
|
||||
|
||||
In modern JavaScript frameworks, DOM elements are regularly `re-rendered` - meaning that the old element is thrown away and a new one is put in its place. Because this happens so fast, it may *appear* as if nothing has visibly changed. But if you are in the middle of executing commands it's possible the element you're interacting with has become "dead". To deal with this situation you must:
|
||||
|
||||
- understand when your application re-renders
|
||||
- re-query for newly added DOM elements
|
||||
- **guard** Cypress from executing commands until a condition is met
|
||||
|
||||
When we say **guard** we mean writing commands in such a way that prevents Cypress from going on before a specific condition is met. This usually means:
|
||||
|
||||
- writing an assertion
|
||||
- waiting on an XHR
|
||||
|
||||
***
|
||||
|
||||
# cy.method() failed because the element cannot be interacted with
|
||||
|
||||
You may see a variation of this message for 4 different reasons:
|
||||
|
||||
1. the element is not visible
|
||||
2. the element is being covered by another element
|
||||
3. the element's center is hidden from view
|
||||
4. the element is disabled
|
||||
|
||||
Cypress runs several calculations to ensure an element can *actually* be interacted with like a real user would.
|
||||
|
||||
If you're seeing this error, the solution is often obvious. You may need to add **command guards** due to a timing or animation issue.
|
||||
|
||||
There have been situations where Cypress does not correctly allow you to interact with an element which should be interactive. If that's the case, [open an issue](https://github.com/cypress-io/cypress/issues/new) or force the action to happen.
|
||||
|
||||
If you'd like to override these built-in checks, provide the `{force: true}` option to the action itself. Refer to each command for their available options, additional use cases and argument usage.
|
||||
|
||||
```javascript
|
||||
// we ignore the built in error checking
|
||||
// and force the action to happen
|
||||
// regardless of whether the button is
|
||||
// visible, disabled, or covered by another element
|
||||
cy.get("button").click({force: true}).
|
||||
```
|
||||
|
||||
*Be careful with this option. It's possible to force your tests to pass but your feature may actually be failing.*
|
||||
|
||||
***
|
||||
|
||||
# cy.method() failed because the element is currently animating
|
||||
|
||||

|
||||
|
||||
By default Cypress detects if an element you're trying to interact with is animating. This check ensures that an element is not animating too quickly for a real user to interact with the element. This also prevents some edge cases where actions such as [`type`](https://on.cypress.io/api/type) or [`click`](https://on.cypress.io/api/click) happenening too fast during a transition.
|
||||
|
||||
Cypress will continuously attempt to interact with the element until it eventually times out.
|
||||
|
||||
If you'd like to force Cypress to interact with the element there are a few options:
|
||||
|
||||
- Pass `{force: true}` and disables **all** error checking
|
||||
- Pass `{waitForAnimations: false}` to disable animation error checking only
|
||||
- Pass `{animationDistanceThreshold: 20}` to decrease the sensitivity to detecting if an element is animating too quickly for a user to interact with. By increasing the threshold this enables your element to move farther on the page without causing Cypress to continuously retry.
|
||||
|
||||
```javascript
|
||||
cy.get("#modal button").click({waitForAnimations: false})
|
||||
```
|
||||
|
||||
You can globally disable animation error checking, or increase the threshold by modifying your [`cypress.json`](https://on.cypress.io/guides/configuration).
|
||||
|
||||
```json
|
||||
// cypress.json
|
||||
{
|
||||
"waitForAnimations": false,
|
||||
"animationDistanceThreshold": 50
|
||||
}
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
# Running Cypress in CI requires a secret project key
|
||||
|
||||
You may receive this error when trying to run Cypress tests in Continuous Integration. This means that you did not pass a specific key to: `cypress ci` in your CI configuration file.
|
||||
|
||||
Since no key was passed, Cypress then checks for any environment variable with the name `CYPRESS_CI_KEY`, but still didn't find any.
|
||||
|
||||
You can get your project's secret key by running the terminal command: `cypress get:key`
|
||||
|
||||
Then [add the key to your config file or as an environment variable](https://on.cypress.io/guides/continuous-integration#section-acquire-a-cypress-secret-key).
|
||||
|
||||
***
|
||||
|
||||
# The test has finished but Cypress still has commands in its queue
|
||||
|
||||

|
||||
|
||||
Let's examine several different ways you may get this error message. In every situation, you'll need to change something in your code to prevent this error.
|
||||
|
||||
{% note warning Flaky tests below! %}
|
||||
Several of these tests are dependent on race conditions. You may have to run these tests multiple times before they will actually fail. You can also try tweaking some of the delays.
|
||||
{% endnote %}
|
||||
|
||||
## Simple Example
|
||||
|
||||
```javascript
|
||||
describe("simple example", function(){
|
||||
// this first test will actually pass and shows you that
|
||||
// Cypress attempts to prevent this problem in every test
|
||||
it("Cypress is smart and this does not fail", function(){
|
||||
// queue up some commands
|
||||
// without returning the cy object
|
||||
// which is ok!
|
||||
cy
|
||||
.get("body")
|
||||
.children()
|
||||
.should("not.contain", "foo")
|
||||
|
||||
// even though we return the string here
|
||||
// Cypress automatically figures out that you've
|
||||
// queued commands above and does not end the test
|
||||
// until all commands have finished
|
||||
return "foobarbaz"
|
||||
})
|
||||
|
||||
it("but you can forcibly end the test early which does fail", function(done){
|
||||
// this example will fail because you've forcibly terminated
|
||||
// the test early with mocha
|
||||
cy
|
||||
.get("body")
|
||||
.then(function(){
|
||||
// forcibly end the test
|
||||
// even though there are still
|
||||
// pending queued commands below
|
||||
done()
|
||||
})
|
||||
.children()
|
||||
.should("not.contain", "foo")
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Complex Async Example
|
||||
|
||||
```javascript
|
||||
describe("a complex example with async code", function(){
|
||||
it("you can cause commands to bleed into the next test", function(){
|
||||
// what's happening here is that because we have NOT told mocha this is an async test
|
||||
// this test will pass immediately and move onto the next test...
|
||||
//
|
||||
// ...then, when the setTimeout callback function runs
|
||||
// new commands will get queued on the wrong test
|
||||
//
|
||||
// Cypress will detect this and fail the next test
|
||||
setTimeout(function(){
|
||||
cy.get("body").children().should("not.contain", "foo")
|
||||
}, 10)
|
||||
|
||||
// the correct way to write the above test code would be this:
|
||||
// it("does not cause commands to bleed into the next test", function(done){
|
||||
// setTimeout(function(){
|
||||
// cy.get("body").children().should("not.contain", "foo").then(function(){
|
||||
// now all the commands are correctly processed on this test
|
||||
// and do not bleed into the next test
|
||||
// done()
|
||||
// })
|
||||
// }, 10)
|
||||
// })
|
||||
|
||||
})
|
||||
|
||||
it("this test will fail due to the previous poorly written test", function(){
|
||||
// we will get the error here that Cypress detected
|
||||
// it still had commands in its command queue
|
||||
//
|
||||
// Cypress will print the commands out which should
|
||||
// help us figure out that the previous test is
|
||||
// causing this error message
|
||||
cy.wait(10)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Complex Promise Example
|
||||
|
||||
```javascript
|
||||
describe("another complex example using a forgotten 'return'", function(){
|
||||
it("forgets to return a promise", function(){
|
||||
// we forget to return the promise to our test
|
||||
// which means the test passes synchronously but
|
||||
// our promise resolves during the next test.
|
||||
//
|
||||
// this causes the commands to be queued on the
|
||||
// wrong test
|
||||
Cypress.Promise.delay(10).then(function(){
|
||||
cy.get("body").children().should("not.contain", "foo")
|
||||
})
|
||||
|
||||
// the correct way to write the above test code would be this:
|
||||
// it("does not forget to return a promise", function(){
|
||||
// return Cypress.Promise.delay(10).then(function(){
|
||||
// return cy.get("body").children().should("not.contain", "foo")
|
||||
// })
|
||||
// }
|
||||
})
|
||||
|
||||
it("this test will fail due to the previous poorly written test", function(){
|
||||
// we will get the error here that Cypress detected
|
||||
// it still had commands in its command queue
|
||||
//
|
||||
// Cypress will print the commands out which should
|
||||
// help us figure out that the previous test is
|
||||
// causing this error message
|
||||
cy.wait(10)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
# cy.visit() failed because you are attempting to visit a second unique domain
|
||||
|
||||
TBD.
|
||||
|
||||
***
|
||||
|
||||
# Cypress detected a cross origin error happened on page load
|
||||
|
||||
{% note info This is a simple overview... %}
|
||||
For a more thorough explanation of Cypress's Web Security model, [please read our dedicated guide to it](https://on.cypress.io/guides/web-security).
|
||||
{% endnote %}
|
||||
|
||||
This error means that your application navigated to a superdomain that Cypress was not bound to.
|
||||
|
||||
Initially when you `cy.visit` Cypress changes the url to match what you are visiting. This enables Cypress to communicate with your appliation to control it, and bypasses all same-origin security policies built into the browsers.
|
||||
|
||||
When your application navigates to a superdomain outside of the current origin-policy Cypress is unable to communicate with it, and thus fails.
|
||||
|
||||
There are generally fairly simple workarounds for these common situations:
|
||||
|
||||
1. Don't click `<a>` links that navigate you outside of your apps. Likely this isn't worth testing anyway. You should ask yourself: *What's the point of clicking and going to another app?* Likely all you care about is that the `href` attribute matches what you expect. So simply make an assertion about that.
|
||||
|
||||
2. You are testing a page that uses `Single sign-on (SSO)`. In this case your webserver is likely redirecting you between superdomains, and thus you receive this error message. You can likely get around this redirect problem by using [`cy.request`](https://on.cypress.io/api/request) and manually handling the session yourself.
|
||||
|
||||
If you find yourself stuck and cannot work around these issues you can just set this in your `cypress.json` file:
|
||||
|
||||
```javascript
|
||||
// cypress.json
|
||||
{
|
||||
chromeWebSecurity: false
|
||||
}
|
||||
```
|
||||
|
||||
But before doing so you should really understand and [read about the reasoning here](https://on.cypress.io/guides/web-security).
|
||||
|
||||
***
|
||||
|
||||
# Support file missing or invalid
|
||||
|
||||
The `supportFolder` option has been removed from Cypress and has been replaced by module support and the `supportFile` option. Cypress used to automatically include any scripts in the `supportFolder` before your test files, and that was the best way to include custom Cypress commands and utility functions. However, automatically including all the files in a certain directory is somewhat magical and unintuitive, and requires creating globals for the purpose of utility functions. This behavior has been succeeded by module support and the `supportFile` option.
|
||||
|
||||
## Use modules for utility functions
|
||||
|
||||
Cypress supports both ES2015 modules and CommonJS modules. You can import/require npm modules as well as local modules:
|
||||
|
||||
```javascript
|
||||
import _ from "lodash"
|
||||
import util from "./util"
|
||||
|
||||
it("uses modules", function () {
|
||||
expect(_.kebabCase("FooBar")).to.equal("foo-bar")
|
||||
expect(util.secretCode()).to.equal("1-2-3-4")
|
||||
})
|
||||
```
|
||||
|
||||
## Use supportFile to load scripts before your test code
|
||||
|
||||
It's still useful to load a setup file before your test code. If you are setting Cypress defaults or utilizing custom Cypress commands, instead of needing to import/require those defaults/commands in every test file, you can use the `supportFile` configuration option. This works similar to the former `supportFolder` option, but is more explicit.
|
||||
|
||||
`supportFile` is a path to a file to include before your test files. By default, `supportFile` is set to look for one of the following files:
|
||||
|
||||
* `cypress/support/index.js`
|
||||
* `cypress/support/index.coffee`
|
||||
|
||||
Just like with your test files, the `supportFile` can use ES2015+ (or CoffeeScript) and modules, so you can import/require other files as needed.
|
||||
|
||||
## Migrating from supportFolder to supportFile
|
||||
|
||||
You're seeing this error because you have the `supportFolder` option explicitly set, either to a different directory or as `false`, meaning you didn't utilize the support folder functionality.
|
||||
|
||||
{% note info I have `supportFolder` set to `false` %}
|
||||
undefined
|
||||
{% endnote %}
|
||||
|
||||
Set the `supportFile` option to `false` instead:
|
||||
|
||||
```javascript
|
||||
// cypress.json
|
||||
|
||||
// before
|
||||
{
|
||||
"supportFolder": false
|
||||
}
|
||||
|
||||
// after
|
||||
{
|
||||
"supportFile": false
|
||||
}
|
||||
```
|
||||
|
||||
{% note info I have `supportFolder` set to a different directory %}
|
||||
undefined
|
||||
{% endnote %}
|
||||
|
||||
When you open a project with Cypress, we look for a file named `index.js` in the `supportFolder` you have set. If one is not present, we generate a file that imports all the other files in your `supportFolder`.
|
||||
|
||||
You simply need to set the `supportFile` option to point to that file, and everything should work as before.
|
||||
|
||||
If, for example, you had the `supportFolder` set to `utilities`, change its name to `supportFile` and its value to `utilities/index.js`:
|
||||
|
||||
```javascript
|
||||
// cypress.json
|
||||
|
||||
// before
|
||||
{
|
||||
"supportFolder": "utilities"
|
||||
}
|
||||
|
||||
// after
|
||||
{
|
||||
"supportFile": "utilities/index.js"
|
||||
}
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
# The Chromium Renderer process just crashed
|
||||
|
||||

|
||||
|
||||
Browsers are enormously complex pieces of software, and from time to time they will inconsistently crash *for no good reason*. Crashes are just a part of running automated tests.
|
||||
|
||||
At the moment, we haven't implemented an automatic way to recover from them, but it is actually possible for us to do so. We have an [open issue documenting the steps](https://github.com/cypress-io/cypress/issues/349) we could take to restart the renderer process and continue the run. If you're seeing consistent crashes and would like this implemented, please leave a note in the issue.
|
||||
|
||||
If you are running `Docker` [there is a simple one line fix for this problem documented here](https://github.com/cypress-io/cypress/issues/350).
|
||||
|
||||
***
|
||||
|
||||
# The 'cypress ci' command has been deprecated
|
||||
|
||||
As of version `0.19.0` and CLI versions `0.13.0`, we have deprecated the `cypress ci` command.
|
||||
|
||||
We did this to make it clearer what the difference was between a **regular run** and a **recorded run**.
|
||||
|
||||
Previously to record runs runs you wrote:
|
||||
|
||||
```shell
|
||||
cypress ci <key>
|
||||
```
|
||||
|
||||
Or if you had the environment variable: `CYPRESS_CI_KEY`
|
||||
|
||||
```shell
|
||||
cypress ci
|
||||
```
|
||||
|
||||
You need to rewrite this as:
|
||||
|
||||
```shell
|
||||
cypress run --record --key <record_key>
|
||||
```
|
||||
|
||||
If you were using the environment variable `CYPRESS_CI_KEY`, rename it to`CYPRESS_RECORD_KEY`.
|
||||
|
||||
You can now run and omit the `--key` flag:
|
||||
|
||||
```shell
|
||||
cypress run --record
|
||||
```
|
||||
|
||||
We will automatically apply the record key environment variable.
|
||||
5
docs/themes/cypress/languages/en.yml
vendored
5
docs/themes/cypress/languages/en.yml
vendored
@@ -110,6 +110,10 @@ sidebar:
|
||||
parent: parent
|
||||
parents: parents
|
||||
parentsuntil: parentsUntil
|
||||
pause: pause
|
||||
prev: prev
|
||||
prevall: prevAll
|
||||
prevuntil: prevUntil
|
||||
readfile: readFile
|
||||
reload: reload
|
||||
request: request
|
||||
@@ -145,6 +149,7 @@ sidebar:
|
||||
_: _
|
||||
$: $
|
||||
minimatch: minimatch
|
||||
moment: moment
|
||||
blob: blob
|
||||
promise: promise
|
||||
cypress-api: Cypress API
|
||||
|
||||
@@ -172,3 +172,13 @@ button, select, input, input[type="submit"]::-moz-focus-inner, input[type="butto
|
||||
line-height: 100px;
|
||||
margin: 100px 0;
|
||||
}
|
||||
|
||||
i.fa {
|
||||
&.red {
|
||||
color: $color-red;
|
||||
}
|
||||
|
||||
&.green {
|
||||
color: $color-green;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,13 @@
|
||||
.article-content, .faq {
|
||||
line-height: $line-height;
|
||||
|
||||
hr {
|
||||
border: 0;
|
||||
height: 0;
|
||||
border-top: 1px solid rgba(0, 0, 0, 0.1);
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
|
||||
p {
|
||||
margin-bottom: 15px;
|
||||
word-wrap: break-word;
|
||||
@@ -167,13 +174,17 @@
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
h1 {
|
||||
font-size: 1.6em;
|
||||
font-size: 1.7em;
|
||||
line-height: 1.5em;
|
||||
font-weight: 500;
|
||||
margin: 1.5em 0 0.5em 0;
|
||||
padding: 0;
|
||||
font-family: $font-title;
|
||||
border-top: 2px solid #eee;
|
||||
padding-top: 1.5em;
|
||||
|
||||
&>a {
|
||||
font-weight: 500;
|
||||
@@ -181,10 +192,10 @@
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1em;
|
||||
font-size: 1.3em;
|
||||
line-height: 1.5em;
|
||||
font-weight: 500;
|
||||
margin: 1em 0 1em 0;
|
||||
margin: 2em 0 0.5em 0;
|
||||
font-family: $font-title;
|
||||
|
||||
code {
|
||||
@@ -221,6 +232,16 @@
|
||||
font-family: $font-title;
|
||||
}
|
||||
|
||||
|
||||
&>p>strong {
|
||||
display: inline-block;
|
||||
margin-top: 1.5em;
|
||||
}
|
||||
|
||||
&>h2+p>strong, &>h1+p>strong {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
a {
|
||||
color: $color-link;
|
||||
text-decoration: none;
|
||||
@@ -235,9 +256,22 @@
|
||||
strong {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
em {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
strong>em {
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
border-bottom: 1px solid #ccc;
|
||||
}
|
||||
|
||||
strong + strong>em {
|
||||
color: #bbb;
|
||||
margin-left: 5px;
|
||||
}
|
||||
|
||||
li {
|
||||
margin: 0;
|
||||
|
||||
|
||||
@@ -6,7 +6,12 @@
|
||||
margin-left: -$sidebar-width;
|
||||
display: none;
|
||||
background-color: #f5f5f5;
|
||||
|
||||
ul {
|
||||
list-style: none;
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-title {
|
||||
margin-top: 1.5em;
|
||||
font-size: 1.1em;
|
||||
|
||||
11
docs/themes/cypress/source/css/_partial/toc.scss
vendored
11
docs/themes/cypress/source/css/_partial/toc.scss
vendored
@@ -15,6 +15,10 @@
|
||||
}
|
||||
}
|
||||
|
||||
.toc {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
#article-toc {
|
||||
display: none;
|
||||
float: right;
|
||||
@@ -34,6 +38,7 @@
|
||||
padding-left: 1em;
|
||||
font-size: 0.85em;
|
||||
line-height: 1.5;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
#article-toc-inner {
|
||||
@@ -42,6 +47,10 @@
|
||||
padding: 0 20px;
|
||||
width: $sidebar-width;
|
||||
|
||||
.sidebar-title {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
&:before {
|
||||
content: "";
|
||||
display: table;
|
||||
@@ -59,7 +68,7 @@
|
||||
display: block;
|
||||
color: #999;
|
||||
text-decoration: none;
|
||||
padding: 3px 0 3px 5px;
|
||||
padding: 5px 0 5px 5px;
|
||||
line-height: 1.2;
|
||||
font-size: 0.95em;
|
||||
position: relative;
|
||||
|
||||
@@ -8,6 +8,8 @@ $white-80: rgba(255,255,255,0.8);
|
||||
$white-60: rgba(255,255,255,0.6);
|
||||
|
||||
$color-gray: #999;
|
||||
$color-green: #04C38E;
|
||||
$color-red: #EA4D5C;
|
||||
$color-default: #474a54;
|
||||
$color-border: #e3e3e3;
|
||||
$color-link: #3B94D9;
|
||||
|
||||
Reference in New Issue
Block a user