Introduction to Cypress

Cypress Can Be Simple (Sometimes)

Simplicity is all about getting more done with less typing. Let's look at an example:

describe('Post Resource', () => {
  it('Creating a New Post', () => {
    cy.visit('/posts/new') // 1.

    cy.get('input.post-title') // 2.
      .type('My First Post') // 3.

    cy.get('input.post-body') // 4.
      .type('Hello, world!') // 5.

    cy.contains('Submit') // 6.
      .click() // 7.

    cy.get('h1') // 8.
      .should('contain', 'My First Post')
  })
})
describe('Post Resource', () => {
  it('Creating a New Post', () => {
    cy.mount(<PostBuilder />) // 1.

    cy.get('input.post-title') // 2.
      .type('My First Post') // 3.

    cy.get('input.post-body') // 4.
      .type('Hello, world!') // 5.

    cy.contains('Submit') // 6.
      .click() // 7.

    cy.get('h1') // 8.
      .should('contain', 'My First Post')
  })
})

Can you read this? If you did, it might sound something like this:

  1. Visit page at /posts/new (or mount the PostBuilder component).
  2. Find the <input> with class post-title.
  3. Type "My First Post" into it.
  4. Find the <input> with class post-body.
  5. Type "Hello, world!" into it.
  6. Find the element containing the text Submit.
  7. Click it.
  8. Find the h1 tag, ensure it contains the text "My First Post".

This is a relatively straightforward test, but consider how much code has been covered by it, both on the client and the server!

For the remainder of this guide, we'll explore the basics of Cypress that make this example work. We'll demystify the rules Cypress follows so you can productively test your application to act as much like a user as possible, as well as discuss how to take shortcuts when it's useful.

Querying Elements

Cypress is Like jQuery

If you've used jQuery before, you may be used to querying for elements like this:

$('.my-selector')

In Cypress, querying elements is the same:

cy.get('.my-selector')

In fact, Cypress bundles jQuery and exposes many of its DOM traversal methods to you so you can work with complex HTML structures with ease using APIs you're already familiar with.

// Each Cypress query is equivalent to its jQuery counterpart.
cy.get('#main-content').find('.article').children('img[src^="/static"]').first()

Accessing the DOM elements returned from the query works differently, however:

// This is fine, jQuery returns the element synchronously.
const $jqElement = $('.element')

// This will not work! Cypress does not return the element synchronously.
const $cyElement = cy.get('.element')

Let's look at why this is...

Cypress is Not Like jQuery

Question: What happens when jQuery can't find any matching DOM elements from its selector?

Answer: Oops! It returns an empty jQuery collection. We've got a real object to work with, but it doesn't contain the element we wanted. So we start adding conditional checks and retrying our queries manually.

// $() returns immediately with an empty collection.
const $myElement = $('.element').first()

// Leads to ugly conditional checks
// and worse - flaky tests!
if ($myElement.length) {
  doSomething($myElement)
}

Question: What happens when Cypress can't find any matching DOM elements from its selector?

Answer: No big deal! Cypress automatically retries the query until either:

1. The element is found

cy
  // cy.get() looks for '#element', repeating the query until...
  .get('#element')

  // ...it finds the element!
  // You can now work with it by using .then
  .then(($myElement) => {
    doSomething($myElement)
  })

2. A set timeout is reached

cy
  // cy.get() looks for '#element-does-not-exist', repeating the query until...
  // ...it doesn't find the element before its timeout.
  // Cypress halts and fails the test.
  .get('#element-does-not-exist')

  // ...this code is never run...
  .then(($myElement) => {
    doSomething($myElement)
  })

This makes Cypress robust and immune to dozens of common problems that occur in other testing tools. Consider all the circumstances that could cause querying a DOM element to fail:

  • The DOM has not loaded yet.
  • Your framework hasn't finished bootstrapping.
  • An XHR request hasn't responded.
  • An animation hasn't completed.
  • and on and on...

Before, you'd be forced to write custom code to protect against any and all of these issues: a nasty mashup of arbitrary waits, conditional retries, and null checks littering your tests. Not in Cypress! With built-in retrying and customizable timeouts, Cypress sidesteps all of these flaky issues.

Querying by Text Content

Another way to locate things -- a more human way -- is to look them up by their content, by what the user would see on the page. For this, there's the handy cy.contains() command, for example:

// Find an element in the document containing the text 'New Post'
cy.contains('New Post')

// Find an element within '.main' containing the text 'New Post'
cy.get('.main').contains('New Post')

This is helpful when writing tests from the perspective of a user interacting with your app. They only know that they want to click the button labeled "Submit". They have no idea that it has a type attribute of submit, or a CSS class of my-submit-button.

When Elements Are Missing

As we showed above, Cypress anticipates the asynchronous nature of web applications and doesn't fail immediately the first time an element is not found. Instead, Cypress gives your app a window of time to finish whatever it may be doing!

This is known as a timeout, and most commands can be customized with specific timeout periods (the default timeout is 4 seconds). These Commands will list a timeout option in their API documentation, detailing how to set the number of milliseconds you want to continue to try finding the element.

// Give this element 10 seconds to appear
cy.get('.my-slow-selector', { timeout: 10000 })

You can also set the timeout globally via the configuration setting: defaultCommandTimeout.

Later in this guide we'll go into much more detail about Default Assertions and Timeouts.

Chains of Commands

It's very important to understand the mechanism Cypress uses to chain commands together. It manages a Promise chain on your behalf, with each command yielding a 'subject' to the next command, until the chain ends or an error is encountered. The developer should not need to use Promises directly, but understanding how they work is helpful!

Interacting With Elements

As we saw in the initial example, Cypress allows you to click on and type into elements on the page by using .click() and .type() action commands with a cy.get() or cy.contains() query command. This is a great example of chaining in action. Let's see it again:

cy.get('textarea.post-body').type('This is an excellent post.')

We're chaining .type() onto cy.get(), telling it to type into the subject yielded from the cy.get() query, which will be a DOM element.

Here are even more action commands Cypress provides to interact with your app:

These commands ensure some guarantees about what the state of the elements should be prior to performing their actions.

For example, when writing a .click() command, Cypress ensures that the element is able to be interacted with (like a real user would). It will automatically wait until the element reaches an "actionable" state by:

  • Not being hidden
  • Not being covered
  • Not being disabled
  • Not animating

This also helps prevent flake when interacting with your application in tests. You can usually override this behavior with a force option.

Asserting About Elements

Assertions let you do things like ensuring an element is visible or has a particular attribute, CSS class, or state. Assertions are commands that enable you to describe the desired state of your application. Cypress will automatically wait until your elements reach this state, or fail the test if the assertions don't pass. Here's a quick look at assertions in action:

cy.get(':checkbox').should('be.disabled')

cy.get('form').should('have.class', 'form-horizontal')

cy.get('input').should('not.have.value', 'US')

In each of these examples, it's important to note that Cypress will automatically wait until these assertions pass. This prevents you from having to know or care about the precise moment your elements eventually do reach this state.

We will learn more about assertions later in this guide.

Subject Management

A new Cypress chain always starts with cy.[command], where what is yielded by the command establishes what other commands can be called next (chained).

All commands yield a value.

Each command specifies what value it yields. For example,

  • cy.clearCookies() yields null. You can chain off commands that yield null, as long as the next command doesn't expect to receive a subject.
  • cy.contains() yields a DOM element, allowing further commands to be chained (assuming they expect a DOM subject) like .click() or even cy.contains() again.
  • .click() yields the same subject it was originally given.

Some commands require a previous subject.

  • .click() requires a DOM element from the previous command.
  • .its() requires a subject, but it can be of any type.
  • cy.contains() behaves differently depending on the previous subject. If chained directly off of cy, or if the previous command yielded null, it will look at the entire document. But if the subject is a DOM element, it will only look inside that container.
  • cy.clearCookies() does not require a previous subject - it can be chained off of anything, even .end().

Examples:

This is actually much more intuitive than it sounds.

cy.clearCookies() // Yields null
  .visit('/fixtures/dom.html') // Does not care about the previous subject.

cy.get('.main-container') // Yields an array of matching DOM elements
  .contains('Headlines') // Yields the first DOM element containing content
  .click() // Yields same DOM element from previous command.

Using .then() To Act On A Subject

Want to jump into the command flow and get your hands on the subject directly? No problem, add a .then() to your command chain. When the previous command resolves, it will call your callback function with the yielded subject as the first argument.

If you wish to continue chaining commands after your .then(), you'll need to specify the subject you want to yield to those commands, which you can achieve with a return value other than null or undefined. Cypress will yield that to the next command for you.

Let's look at an example:

cy
  // Find the el with id 'some-link'
  .get('#some-link')

  .then(($myElement) => {
    // ...massage the subject with some arbitrary code

    // grab its href property
    const href = $myElement.prop('href')

    // strip out the 'hash' character and everything after it
    return href.replace(/(#.*)/, '')
  })
  .then((href) => {
    // href is now the new subject
    // which we can work with now
  })

Using Aliases to Refer to Previous Subjects

Cypress has some added functionality for quickly referring back to past subjects called Aliases. It looks something like this:

cy.get('.my-selector')
  .as('myElement') // sets the alias
  .click()

/* many more actions */

cy.get('@myElement') // re-queries the DOM as before
  .click()

This lets us reuse our queries for more readable tests, and it automatically handles re-querying the DOM for us as it updates. This is particularly helpful when dealing with front end frameworks that do a lot of re-rendering!

Commands Are Asynchronous

It is very important to understand that Cypress commands don't do anything at the moment they are invoked, but rather enqueue themselves to be run later. This is what we mean when we say Cypress commands are asynchronous.

Take this short test, for example:

it('hides the thing when it is clicked', () => {
  cy.visit('/my/resource/path') // Nothing happens yet

  cy.get('.hides-when-clicked') // Still nothing happening
    .should('be.visible') // Still absolutely nothing
    .click() // Nope, nothing

  cy.get('.hides-when-clicked') // Still nothing happening
    .should('not.be.visible') // Definitely nothing happening yet
})

// Ok, the test function has finished executing...
// We've queued all of these commands and now
// Cypress will begin running them in order!
it('hides the thing when it is clicked', () => {
  cy.mount(<MyComponent />) // Nothing happens yet

  cy.get('.hides-when-clicked') // Still nothing happening
    .should('be.visible') // Still absolutely nothing
    .click() // Nope, nothing

  cy.get('.hides-when-clicked') // Still nothing happening
    .should('not.be.visible') // Definitely nothing happening yet
})

// Ok, the test function has finished executing...
// We've queued all of these commands and now
// Cypress will begin running them in order!

Cypress doesn't kick off the browser automation until the test function exits.

Mixing Async and Sync code

Remembering that Cypress commands run asynchronously is important if you are attempting to mix Cypress commands with synchronous code. Synchronous code will execute immediately - not waiting for the Cypress commands above it to execute.

Incorrect usage

In the example below, the el evaluates immediately, before the cy.visit() has executed, so will always evaluate to an empty array.

it('does not work as we expect', () => {
  cy.visit('/my/resource/path') // Nothing happens yet

  cy.get('.awesome-selector') // Still nothing happening
    .click() // Nope, nothing

  // Cypress.$ is synchronous, so evaluates immediately
  // there is no element to find yet because
  // the cy.visit() was only queued to visit
  // and did not actually visit the application
  let el = Cypress.$('.new-el') // evaluates immediately as []

  if (el.length) {
    // evaluates immediately as 0
    cy.get('.another-selector')
  } else {
    // this will always run
    // because the 'el.length' is 0
    // when the code executes
    cy.get('.optional-selector')
  }
})

// Ok, the test function has finished executing...
// We've queued all of these commands and now
// Cypress will begin running them in order!

Correct usage

Below is one way the code above could be rewritten in order to ensure the commands run as expected.

it('does not work as we expect', () => {
  cy.visit('/my/resource/path') // Nothing happens yet

  cy.get('.awesome-selector') // Still nothing happening
    .click() // Nope, nothing
    .then(() => {
      // placing this code inside the .then() ensures
      // it runs after the cypress commands 'execute'
      let el = Cypress.$('.new-el') // evaluates after .then()

      if (el.length) {
        cy.get('.another-selector')
      } else {
        cy.get('.optional-selector')
      }
    })
})

// Ok, the test function has finished executing...
// We've queued all of these commands and now
// Cypress will begin running them in order!

Incorrect usage

In the example below, the check on the username value gets evaluated immediately, before the cy.visit() has executed, so will always evaluate to undefined.

it('test', () => {
  let username = undefined // evaluates immediately as undefined

  cy.visit('https://app.com') // Nothing happens yet
  cy.get('.user-name') // Still, nothing happens yet
    .then(($el) => {
      // Nothing happens yet
      // this line evaluates after the .then executes
      username = $el.text()
    })

  // this evaluates before the .then() above
  // so the username is still undefined
  if (username) {
    // evaluates immediately as undefined
    cy.contains(username).click()
  } else {
    // this will always run
    // because username will always
    // evaluate to undefined
    cy.contains('My Profile').click()
  }
})

// Ok, the test function has finished executing...
// We've queued all of these commands and now
// Cypress will begin running them in order!

Correct usage

Below is one way the code above could be rewritten in order to ensure the commands run as expected.

it('test', () => {
  let username = undefined // evaluates immediately as undefined

  cy.visit('https://app.com') // Nothing happens yet
  cy.get('.user-name') // Still, nothing happens yet
    .then(($el) => {
      // Nothing happens yet
      // this line evaluates after the .then() executes
      username = $el.text()

      // evaluates after the .then() executes
      // it's the correct value gotten from the $el.text()
      if (username) {
        cy.contains(username).click()
      } else {
        cy.get('My Profile').click()
      }
    })
})

// Ok, the test function has finished executing...
// We've queued all of these commands and now
// Cypress will begin running them in order!

Avoid loops

Using JavaScript loop commands like while can have unexpected effects. Let's say our application shows a random number on load.

Manually reloading the browser page until the number 7 appears

We want the test to stop when it finds the number 7. If any other number is displayed the test reloads the page and checks again.

Note: you can find this application and the correct test in our Recipes.

Incorrect test

The test written below WILL NOT work and most likely will crash your browser.

let found7 = false

while (!found7) {
  // this schedules an infinite number
  // of "cy.get..." commands, eventually crashing
  // before any of them have a chance to run
  // and set found7 to true
  cy.get('#result')
    .should('not.be.empty')
    .invoke('text')
    .then(parseInt)
    .then((number) => {
      if (number === 7) {
        found7 = true
        cy.log('lucky **7**')
      } else {
        cy.reload()
      }
    })
}

The above test keeps adding more cy.get('#result') commands to the test chain without executing any! The chain of commands keeps growing, but never executes - since the test function never finishes running. The while loop never allows Cypress to start executing even the very first cy.get(...) command.

Correct test

We need to give the test a chance to run a few commands before deciding if it needs to continue. Thus the correct test would use recursion.

const checkAndReload = () => {
  // get the element's text, convert into a number
  cy.get('#result')
    .should('not.be.empty')
    .invoke('text')
    .then(parseInt)
    .then((number) => {
      // if the expected number is found
      // stop adding any more commands
      if (number === 7) {
        cy.log('lucky **7**')

        return
      }

      // otherwise insert more Cypress commands
      // by calling the function after reload
      cy.wait(500, { log: false })
      cy.reload()
      checkAndReload()
    })
}

cy.visit('public/index.html')
checkAndReload()

The test runs and correctly finishes.

Test reloads the page until the number 7 appears

You can see a short video going through this example at https://www.youtube.com/watch?v=5Z8BaPNDfvA.

Commands Run Serially

After a test function is finished running, Cypress goes to work executing the commands that were enqueued using the cy.* command chains.

Let's take another look at an example

it('hides the thing when it is clicked', () => {
  cy.visit('/my/resource/path') // 1

  cy.get('.hides-when-clicked') // 2
    .should('be.visible') // 3
    .click() // 4

  cy.get('.hides-when-clicked') // 5
    .should('not.be.visible') // 6
})
it('hides the thing when it is clicked', () => {
  cy.mount(<MyComponent />) // 1

  cy.get('.hides-when-clicked') // 2
    .should('be.visible') // 3
    .click() // 4

  cy.get('.hides-when-clicked') // 5
    .should('not.be.visible') // 6
})

The test above would cause an execution in this order:

  1. Visit the URL (or mount the component).
  2. Find an element by its selector.
  3. Assert that the element is visible.
  4. Perform a click action on that element.
  5. Find an element by its selector.
  6. Assert that the element is no longer visible.

These actions will always happen serially (one after the other), never in parallel (at the same time). Why?

To illustrate this, let's revisit that list of actions and expose some of the hidden ✨ magic ✨ Cypress does for us at each step:

  1. Visit the URL ✨ and wait for the page load event to fire after all external resources have loaded ✨ (or mount the component ✨ and wait for the component to finish mounting ✨)
  2. Find an element by its selector ✨ and retry until it is found in the DOM
  3. Assert that the element is visible ✨ and retry until the assertion passes
  4. Perform a click action on that element ✨ after we wait for the element to reach an actionable state
  5. Find an element by its selector ✨ and retry until it is found in the DOM
  6. Assert that the element is no longer visible ✨ and retry until the assertion passes

As you can see, Cypress does a lot of extra work to ensure the state of the application matches what our commands expect about it. Each command may resolve quickly (so fast you won't see them in a pending state) but others may take seconds, or even dozens of seconds to resolve.

While most commands time out after a few seconds, other specialized commands that expect particular things to take much longer like cy.visit() will naturally wait longer before timing out.

These commands have their own particular timeout values which are documented in the Cypress configuration.

The Cypress Command Queue

While the API may look similar to Promises, with it's then() syntax, Cypress commands and queries are not promises - they are serial commands passed into a central queue, to be executed asynchronously at a later date. These commands are designed to deliver deterministic, repeatable and consistent tests.

Almost all commands come with built-in retry-ability. Without retry-ability, assertions would randomly fail. This would lead to flaky, inconsistent results.

Commands also have some design choices that developers who are used to promise-based testing may find unexpected. They are intentional decisions on Cypress' part, not technical limitations.

  1. You cannot race or run multiple commands at the same time (in parallel).
  2. You cannot add a .catch error handler to a failed command.

The whole purpose of Cypress (and what makes it very different from other testing tools) is to create consistent, non-flaky tests that perform identically from one run to the next. Making this happen isn't free - there are some trade-offs we make that may initially seem unfamiliar to developers accustomed to working with Promises or other libraries.

Let's take a look at each trade-off in depth:

You cannot race or run multiple commands at the same time

Cypress guarantees that it will execute all of its commands and queries deterministically and identically every time they are run.

A lot of Cypress commands mutate the state of the browser in some way.

  • cy.request() automatically gets + sets cookies to and from the remote server.
  • cy.clearCookies() clears all of the browser cookies.
  • .click() causes your application to react to click events.

None of the above commands are idempotent; they all cause side effects. Racing commands is not possible because commands must be run in a controlled, serial manner in order to create consistency. Because integration and e2e tests primarily mimic the actions of a real user, Cypress models its command execution model after a real user working step by step.

You cannot add a .catch error handler to a failed command

In Cypress there is no built in error recovery from a failed command. A command and its assertions all eventually pass, or if one fails, all remaining commands are not executed, and the test fails.

You might be wondering:

How do I create conditional control flow, using if/else? So that if an element does (or doesn't) exist, I choose what to do?

The problem with this question is that this type of conditional control flow ends up being non-deterministic. This means different test runs may behave differently, which makes them less deterministic and consistent. In general, there are only a handful of very specific situations where you can create control flow using Cypress commands.

With that said, as long as you are aware of the potential pitfalls with control flow, it is possible to do this in Cypress!

You can read all about how to do conditional testing here.

Assertions

As we mentioned previously in this guide:

Assertions describe the desired state of your elements, your objects, and your application.

What makes Cypress unique from other testing tools is that commands automatically retry their assertions. In fact, they will look "downstream" at what you're expressing and modify their behavior to make your assertions pass.

You should think of assertions as guards.

Use your guards to describe what your application should look like, and Cypress will automatically block, wait, and retry until it reaches that state.

Asserting in English

Let's look at how you'd describe an assertion in English:

After clicking on this <button>, I expect its class to eventually be active.

To express this in Cypress you'd write:

cy.get('button').click()
cy.get('button').should('have.class', 'active')

This above test will pass even if the .active class is applied to the button asynchronously - or after an indeterminate period of time.

// even though we are adding the class
// after two seconds...
// this test will still pass!
$('button').on('click', (e) => {
  setTimeout(() => {
    $(e.target).addClass('active')
  }, 2000)
})

Here's another example.

After making an HTTP request to my server, I expect the response body to equal {name: 'Jane'}

To express this with an assertion you'd write:

cy.request('/users/1').its('body').should('deep.eq', { name: 'Jane' })

When To Assert?

Despite the dozens of assertions Cypress makes available to you, sometimes the best test may make no assertions at all! How can this be? Aren't assertions a basic part of testing?

Consider this example:

cy.visit('/home')

cy.get('.main-menu').contains('New Project').click()

cy.get('.title').type('My Awesome Project')

cy.get('form').submit()
cy.mount(<MyComponent />)

cy.get('.main-menu').contains('New Project').click()

cy.get('.title').type('My Awesome Project')

cy.get('form').submit()

Without a single explicit assertion, there are dozens of ways this test can fail! Here's a few:

  • The initial cy.mount() or cy.visit() could respond with something other than success.
  • Any of the cy.get() queries could fail to find their elements in the DOM.
  • The element we want to .click() on could be covered by another element.
  • The input we want to .type() into could be disabled.
  • Form submission could result in a non-success status code.
  • The in-page JS (the application under test) or the component could throw an error.

Default Assertions

Many commands have default, built-in assertions, or rather have requirements that may cause it to fail without needing an explicit assertion you've added.

For instance:

  • cy.visit() expects the page to send text/html content with a 200 status code.
  • cy.request() expects the remote server to exist and provide a response.
  • cy.contains() expects the element with content to eventually exist in the DOM.
  • cy.get() expects the element to eventually exist in the DOM.
  • .find() also expects the element to eventually exist in the DOM.
  • .type() expects the element to eventually be in a typeable state.
  • .click() expects the element to eventually be in an actionable state.
  • .its() expects to eventually find a property on the current subject.

Certain commands may have a specific requirement that causes them to immediately fail without retrying, such as cy.request().

Others, such as DOM queries automatically retry and wait for their corresponding elements to exist before failing.

Action commands automatically wait for their element to reach an actionable state before failing.

Most commands give you the flexibility to override or bypass the default ways they can fail, typically by passing a {force: true} option.

Example #1: Existence and Actionability

cy
  // there is a default assertion that this
  // button must exist in the DOM before proceeding
  .get('button')

  // before issuing the click, this button must be "actionable"
  // it cannot be disabled, covered, or hidden from view.
  .click()

Cypress will automatically wait for elements to pass their default assertions. Like with the explicit assertions you've added, all of these assertions share the same timeout values.

Example #2: Reversing the Default Assertion

Most of the time, when querying for elements, you expect them to eventually exist. But sometimes you wish to wait until they don't exist.

All you have to do is add that assertion and Cypress will reverse its rules waiting for elements to exist.

cy.get('button.close').click()

// now Cypress will wait until this
// <button> is not in the DOM
cy.get('button.close').should('not.exist')

// and now make sure this #modal does not exist in the DOM
// and automatically wait until it's gone!
cy.get('#modal').should('not.exist')

Example #3: Other Default Assertions

Other commands have other default assertions not related to the DOM.

For instance, .its() requires that the property you're asking about exists on the object.

// create an empty object
const obj = {}

// set the 'foo' property after 1 second
setTimeout(() => {
  obj.foo = 'bar'
}, 1000)

// .its() will wait until the 'foo' property is on the object
cy.wrap(obj).its('foo')

List of Assertions

Cypress bundles Chai, Chai-jQuery, and Sinon-Chai to provide built-in assertions. You can see a comprehensive list of them in the list of assertions reference. You can also write your own assertions as Chai plugins and use them in Cypress.

Writing Assertions

There are two ways to write assertions in Cypress:

  1. Implicit Subjects: Using .should() or .and().
  2. Explicit Subjects: Using expect.

Implicit Subjects

Using .should() or .and() commands is the preferred way of making assertions in Cypress. These are typical Cypress commands, which means they apply to the currently yielded subject in the command chain.

// the implicit subject here is the first <tr>
// this asserts that the <tr> has an .active class
cy.get('tbody tr:first').should('have.class', 'active')

You can chain multiple assertions together using .and(), which is another name for .should() that makes things more readable:

cy.get('#header a')
  .should('have.class', 'active')
  .and('have.attr', 'href', '/users')

Because .should('have.class') does not change the subject, .and('have.attr') is executed against the same element. This is handy when you need to assert multiple things against a single subject quickly.

If we wrote this assertion in the explicit form "the long way", it would look like this:

cy.get('tbody tr:first').should(($tr) => {
  expect($tr).to.have.class('active')
  expect($tr).to.have.attr('href', '/users')
})

The implicit form is much shorter! So when would you want to use the explicit form?

Typically when you want to:

  • Assert multiple things about the same subject
  • Massage the subject in some way prior to making the assertion

Explicit Subjects

Using expect allows you to pass in a specific subject and make an assertion about it. This is probably how you're used to seeing assertions written in unit tests:

// the explicit subject here is the boolean: true
expect(true).to.be.true

Explicit assertions are great when you want to:

  • Perform custom logic prior to making the assertion.
  • Make multiple assertions against the same subject.

The .should() assertion allows us to pass a callback function that takes the yielded subject as its first argument. This works like .then(), except Cypress automatically waits and retries for everything inside of the callback function to pass.

cy.get('p').should(($p) => {
  // massage our subject from a DOM element
  // into an array of texts from all of the p's
  let texts = $p.map((i, el) => {
    return Cypress.$(el).text()
  })

  // jQuery map returns jQuery object
  // and .get() converts this to an array
  texts = texts.get()

  // array should have length of 3
  expect(texts).to.have.length(3)

  // with this specific content
  expect(texts).to.deep.eq([
    'Some text from first p',
    'More text from second p',
    'And even more text from third p',
  ])
})

Timeouts

Almost all commands can time out in some way.

All assertions, whether they're the default ones or whether they've been added by you all share the same timeout values.

Applying Timeouts

You can modify a commands's timeout. This timeout affects both its default assertions (if any) and any specific assertions you've added.

Remember because assertions are used to describe a condition of the previous commands - the timeout modification goes on the previous commands not the assertions.

Example #1: Default Assertion

// because .get() has a default assertion
// that this element exists, it can time out and fail
cy.get('.mobile-nav')

Under the hood Cypress:

  • Queries for the element .mobile-nav

    and waits up to 4 seconds for it to exist in the DOM

Example #2: Additional Assertions

// we've added 2 assertions to our test
cy.get('.mobile-nav').should('be.visible').and('contain', 'Home')

Under the hood Cypress:

  • Queries for the element .mobile-nav

    and waits up to 4 seconds for it to exist in the DOM✨ ✨and be visible✨ ✨and contain the text: Home

The total amount of time Cypress will wait for all of the assertions to pass is for the duration of the cy.get() timeout (which is 4 seconds).

Timeouts can be modified per command and this will affect all default assertions and any assertions chained after that command.

Example #3: Modifying Timeouts

// we've modified the timeout which affects default
// plus all added assertions
cy.get('.mobile-nav', { timeout: 10000 })
  .should('be.visible')
  .and('contain', 'Home')

Under the hood Cypress:

  • Gets the element .mobile-nav

    and waits up to 10 seconds for it to exist in the DOM✨ ✨and be visible✨ ✨and contain the text: Home

Notice that this timeout has flowed down to all assertions and Cypress will now wait up to 10 seconds total for all of them to pass.

Default Values

Cypress offers several different timeout values based on the type of command.

We've set their default timeout durations based on how long we expect certain actions to take.

For instance:

  • cy.visit() loads a remote page and does not resolve until all of the external resources complete their loading phase. This may take awhile, so its default timeout is set to 60000ms.
  • cy.exec() runs a system command such as seeding a database. We expect this to potentially take a long time, and its default timeout is set to 60000ms.
  • cy.wait() actually uses 2 different timeouts. When waiting for a routing alias, we wait for a matching request for 5000ms, and then additionally for the server's response for 30000ms. We expect your application to make a matching request quickly, but we expect the server's response to potentially take much longer.

That leaves most other commands including all DOM queries to time out by default after 4000ms.