docs: Converted should - uncheck

This commit is contained in:
Jennifer Shehane
2017-05-31 12:15:28 -04:00
parent 443ec04e7c
commit f7bf7d6c19
14 changed files with 640 additions and 420 deletions
+1 -1
View File
@@ -47,7 +47,7 @@ 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`.
Pass in an options object to change the default behavior of `.check()`.
Option | Default | Notes
--- | --- | ---
+42 -50
View File
@@ -17,17 +17,17 @@ The clock starts at the unix epoch (timestamp of 0). This means that when you in
# Syntax
```javascript
.clock()
.clock(now)
.clock(now, functionNames)
.clock(options)
.clock(now, options)
.clock(now, functionNames, options)
cy.clock()
cy.clock(now)
cy.clock(now, functionNames)
cy.clock(options)
cy.clock(now, options)
cy.clock(now, functionNames, options)
```
## Usage
`.clock()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
`cy.clock()` cannot be chained off any other cy commands, so should be chained off of `cy` for clarity.
**{% fa fa-check-circle green %} Valid Usage**
@@ -47,7 +47,7 @@ Name of native functions that clock should override.
**{% fa fa-angle-right %} options** ***(Object)***
Pass in an options object to change the default behavior of `.clock`.
Pass in an options object to change the default behavior of `cy.clock()`.
Option | Default | Notes
--- | --- | ---
@@ -55,15 +55,17 @@ Option | Default | Notes
## Yields
`.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.
`cy.clock()` yields a `clock` object with the following methods.
**clock.tick(*milliseconds*)**
**`clock.tick(milliseconds)`**
Move the clock the specified number of `milliseconds`. Any timers within the affected range of time will be called.
**clock.restore()**
**`clock.restore()`**
Restore all overridden native functions. This is automatically called between tests, so should generally not be needed.
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
@@ -83,20 +85,17 @@ setInterval(function(){
```
```javascript
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')
```
**Access the clock object to synchronously move time**
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 `.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) {
@@ -107,29 +106,26 @@ cy.clock().then(function (clock) {
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**
In general, it should not be necessary to manually restore the native functions that `.clock()` overrides, since this is done automatically between tests. But if you need to, the `clock` object yielded has a `.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) {
@@ -140,12 +136,11 @@ 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 ...
})
```
## Now
@@ -160,11 +155,9 @@ $('#date').text(new Date().toJSON())
```javascript
const now = new Date(2017, 2, 14).getTime() // March 14, 2017 timestamp
cy
.clock(now)
.visit('/index.html')
.get('#date')
.contains('2017-03-14')
cy.clock(now)
cy.visit('/index.html')
cy.get('#date').contains('2017-03-14')
```
## Function Names
@@ -196,9 +189,8 @@ If you call `cy.clock` before visiting a page with [`cy.visit`](https://on.cypre
**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:
+8 -3
View File
@@ -4,12 +4,17 @@ comments: true
description: ''
---
Get the current URL hash. This is the same as [`.location().hash`](https://on.cypress.io/api/location)
Get the current URL hash.
{% note info %}
This is the same as [`cy.location().hash`](https://on.cypress.io/api/location)
{% endnote %}
# Syntax
```javascript
.hash(options)
cy.hash()
cy.hash(options)
```
## Usage
@@ -26,7 +31,7 @@ cy.hash()
**{% fa fa-angle-right %} options** ***(Object)***
Pass in an options object to change the default behavior of `.hash()`.
Pass in an options object to change the default behavior of `cy.hash()`.
**cy.hash( *options* )**
+23
View File
@@ -182,6 +182,29 @@ cy
})
```
**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>`)
+6 -4
View File
@@ -4,7 +4,7 @@ comments: true
description: ''
---
Expand an expression into multiple arguments.
Expand an array into multiple arguments.
{% note info %}
Similar of [`.then()`](https://on.cypress.io/api/then), but always expects an array as it's subject.
@@ -13,7 +13,7 @@ Similar of [`.then()`](https://on.cypress.io/api/then), but always expects an ar
# Syntax
```javascript
.spread(function() {})
.spread(fn)
```
## Usage
@@ -35,12 +35,14 @@ cy.location().spread() // Errors, 'location' does not yield an array
## Arguments
**{% fa fa-angle-right %} function** ***(Function)***
**{% fa fa-angle-right %} fn** ***(Function)***
Pass a function that expands the array into it's arguments. Whatever was passed to the function is what is yielded.
Pass a function that expands the array into it's arguments.
## Yields
Whatever was passed to the function is what is yielded.
## Timeout
# Examples
+2 -3
View File
@@ -6,7 +6,6 @@ description: ''
Wrap a method in a spy in order to record calls to and arguments of the function.
# Syntax
```javascript
@@ -20,7 +19,7 @@ cy.spy(object, method)
**{% fa fa-check-circle green %} Valid Usage**
```javascript
cy.stub(user, 'addFriend')
cy.spy(user, 'addFriend')
```
## Arguments
@@ -62,7 +61,7 @@ expect(util.addListeners).to.be.called
## Alias a spy
Adding an alias using [`.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 = {
+34 -30
View File
@@ -39,86 +39,75 @@ The name of the `method` on the `object` to be wrapped.
The function used to replaces the `method` on the `object`.
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.
`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.
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`.
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.
## 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')
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 () {
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)
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 = {
@@ -126,6 +115,7 @@ const obj = {
}
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
@@ -135,9 +125,23 @@ You will see the following in the command log:
![stubs with aliases](https://cloud.githubusercontent.com/assets/1157043/22437243/4cc778a4-e6f5-11e6-8f07-e601d3438c4f.png)
# 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 = {
+38 -21
View File
@@ -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,14 +58,12 @@ Option | Default | Notes
```
```javascript
// submits the form and performs all default actions
// returns <form> for further chaining
cy.get('#contact').submit()
```
# Command Log
## Submit a form
**Submit a form**
```javascript
cy.route('POST', '/users', 'fixture:user').as('userSuccess')
+83 -85
View File
@@ -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">
@@ -33,50 +64,13 @@ 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
// 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(){
@@ -87,38 +81,7 @@ cy.then(function(){
})
```
## Cypress waits for the Promise to resolve before continuing
```javascript
// if using Q
cy.get('button').click().then(function($button){
var p = Q.defer()
setTimeout(function(){
p.resolve()
}, 5000)
return p.promise
})
// if using bluebird
cy.get('button').click().then(function($button){
return Promise.delay(5000)
})
// if using jQuery deferred's
cy.get('button').click().then(function($button){
var df = $.Deferred()
setTimeout(function(){
df.resolve()
}, 5000)
return df
})
```
## Returning `null` or `undefined` will not modify the subject
**Returning `null` or `undefined` will not modify the subject**
```javascript
cy
@@ -134,16 +97,51 @@ cy
})
```
# Options Usage
## Promises
**Cypress waits for the Promise to resolve before continuing**
***Example using Q***
```javascript
cy.then({timeout: 7000}, function(){
// code here
cy.get('button').click().then(function($button){
var p = Q.defer()
setTimeout(function(){
p.resolve()
}, 5000)
return p.promise
})
```
***Example using bluebird***
```javascript
cy.get('button').click().then(function($button){
return Promise.delay(5000)
})
```
***Example using jQuery deferred's***
```javascript
cy.get('button').click().then(function($button){
var df = $.Deferred()
setTimeout(function(){
df.resolve()
}, 5000)
return df
})
```
# 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)
+58 -29
View File
@@ -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:
@@ -66,8 +95,8 @@ When clicking on the `tick` command within the command log, the console outputs
# 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)
+34 -14
View File
@@ -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:
+107 -53
View File
@@ -4,99 +4,147 @@ 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) 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`.
![cypress-command-positions-diagram](https://cloud.githubusercontent.com/assets/1271364/25048528/fe0c6378-210a-11e7-96bc-3773f774085b.jpg)
**[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
cy.get('input[type=range]').as('range')
.invoke('val', 25)
.ttrigger('change')
cy.get('@range').siblings('p').should('have.text', '25')
```
## Position
**Trigger a `mousedown` on the top right of a button**
```javascript
// mousedown is issued in the top right corner of the element
cy.get('button').trigger('mousedown', 'topRight')
```
# Coordinates Usage
## Coordinates
## Specify explicit coordinates relative to the top left corner
**Specify explicit coordinates relative to the top left corner**
```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)
```
# Options Usage
## Options
## Specify that the event should not bubble
**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.
@@ -104,9 +152,15 @@ This overrides the default auto-positioning based on the element itself. Useful
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')
@@ -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
## 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) if you'd like to be able to trigger an event serially on multiple elements.
# See also
- [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)
+151 -98
View File
@@ -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,76 +71,137 @@ 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')
```
{% 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
// 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.
@@ -136,7 +215,7 @@ To keep a modifier activated between commands, specify `{release: false}` in the
```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()
```
@@ -168,21 +247,24 @@ cy.get('input').type('{alt}')
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
// 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
@@ -190,37 +272,17 @@ cy.get('body').type('{uparrow}{uparrow}{downarrow}{downarrow}{leftarrow}{rightar
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.
# Month inputs
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.
# Week inputs
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
**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) if you need this to be fixed.
## Preventing mousedown does not prevent typing
**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) if you need this to be fixed.
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.
## 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.
@@ -242,17 +304,7 @@ This holds true for other special key combinations as well (that may be OS-speci
[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,7 +331,7 @@ 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.
@@ -295,7 +347,7 @@ $('#username').on('keydown', function(e){
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,9 +381,9 @@ 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).
@@ -342,7 +393,7 @@ Any modifiers activated for the event are also listed in a `modifiers` column.
![Cypress cy.type key events table](https://cloud.githubusercontent.com/assets/1157043/18144246/b44df61c-6f93-11e6-8553-96b1b347db4b.png)
## 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,7 +407,7 @@ 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')
@@ -372,6 +423,8 @@ When clicking on `type` within the command log, the console outputs the followin
# 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)
+53 -29
View File
@@ -4,68 +4,92 @@ 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()
```
## Uncheck all radios
```javascript
cy.get('[type="checkbox"]').uncheck()
```
## Uncheck element with the id `saveUserName`
**Uncheck element with the id `saveUserName`**
```javascript
cy.get('#saveUserName').uncheck()
```
# Values Usage
## Value
## Uncheck the checkbox with the value of 'ga'
**Uncheck the checkbox with the value of 'ga'**
```javascript
cy.get('input[type="checkbox"]').uncheck(['ga'])
```
## Values
**Uncheck the checkboxes with the value of 'ga' and 'ca'**
```javascript
cy.get('[type="checkbox"]').uncheck(['ga', 'ca'])
```
# Command Log
## Uncheck the first checkbox
**Uncheck the first checkbox**
```javascript
cy