Home

Awesome

Recipes

CircleCI

<!-- [![Build status](https://ci.appveyor.com/api/projects/status/7p4qkwavheciwbxc/branch/master?svg=true)](https://ci.appveyor.com/project/cypress-io/cypress-example-recipes/branch/master) -->

renovate-app badge Cypress Dashboard

This repo contains various recipes for testing common scenarios using Cypress: Fundamentals, Testing the DOM, Logging in, Preprocessors, Blogs, Stubbing and spying, Unit Testing, Server Communication, Other Cypress Recipes, Community Recipes

Fundamentals

RecipeDescription
Node ModulesImport your own node modules
Environment variablesPassing environment variables to tests
Handling errorsHandling thrown errors and unhandled promise rejections
Dynamic testsCreate tests dynamically from JSON data
Dynamic tests from CSVCreate tests dynamically from CSV file
Dynamic tests from APICreate tests dynamically by calling an external API
FixturesLoading single or multiple fixtures
Adding Custom CommandsWrite your own custom commands using JavaScript with correct types for IntelliSense to work
Adding Custom Commands (TS)Write your own custom commands using TypeScript
Adding Chai AssertionsAdd new or custom chai assertions with correct types
Cypress module APIRun Cypress via its module API
Wrapping Cypress module APIWriting a wrapper around "cypress run" command line parsing
Custom browsersControl which browsers the project can use, or even add a custom browser into the list
Use Chrome Remote InterfaceUse Chrome debugger protocol to trigger hover state and print media style
Out-of-the-box TypeScriptWrite tests in TypeScript without setting up preprocessors
Per-test timeoutFail a test if it runs longer than the specified time limit
Cypress eventsUsing Cypress.on and cy.on to listen to Cypress events like before:window:load
Video resolutionIncrease the browser window size to record high quality videos and capture detailed screenshots

Testing the DOM

RecipeDescription
Tab Handling and LinksLinks that open in a new tab
Hover and Hidden ElementsTest hidden elements requiring hover
Form InteractionsTest form elements like input type range
Drag and DropUse .trigger() to test drag and drop
Shadow DOMYou need to use any of available custom commands
Waiting for static resourceShows how to wait for CSS, image, or any other static resource to load
CSV load and table testLoads CSV file and quickly compares objects against cells in a table
Evaluate performance metricsUtilize Cypress to monitor a website
Root styleTrigger input color change that modifies CSS variable
Select widgetsWorking with <select> elements and Select2 widgets
Lit ElementsTesting Lit Elements with Shadow DOM
File downloadDownload and validate CSV, Excel, text, Zip, and image files
Page reloadsAvoiding while loop when dealing with randomness
PaginationClicking the "Next" link until we reach the last page
ClipboardCopy and paste text into the clipboard from the test
Page sourceGet the source of the page under test
Responsive imageUses cy.intercept to confirm the image loaded by the <picture> element

Logging in recipes

RecipeDescription
Basic AuthLog in using Basic Authentication
Single Sign OnLog in across multiple servers or providers
HTML Web FormsLog in with a basic HTML form
XHR Web FormsLog in using an XHR
CSRF TokensLog in with a required CSRF token
Json Web Tokens (JWT)Log in using JWT
Using application codeLog in by calling the application code

Also see Authentication plugins and watch video "Organizing Tests, Logging In, Controlling State"

Preprocessors

RecipeDescription
grepFilter tests by name using Mocha-like grep syntax
Typescript with BrowserifyAdd typescript support with browserify
Typescript with WebpackAdd typescript support with webpack
Flow with BrowserifyAdd flow support with browserify

Blogs

Demo recipes from the blog posts at www.cypress.io/blog

RecipeDescription
Application ActionsApplication actions are a replacement for Page Objects
Direct Control of AngularJSBypass the DOM and control AngularJS
E2E API TestingRun your API Tests with a GUI
E2E SnapshotsEnd-to-End Snapshot Testing
Element CoverageTrack elements covered by tests
Codepen.io TestingTest a HyperApp Codepen demo
Testing Redux StoreTest an application that uses Redux data store
Vue + Vuex + REST TestingTest an application that uses central data store
A11y TestingAccessibility testing with cypress-axe
Automate Angular TestingRun Angular tests in a build environment
React DevToolsLoads React DevTools Chrome extension automatically
Expect N assertionsHow to expect a certain number of assertions in a test
Browser notificationsHow to test application that uses Notification
Testing iframesAccessing elements in 3rd party iframe, spy and stub network calls from iframe
Class decoratorsUsing JavaScript class decorator to expose objects created by the application so they are reachable from tests
Form SubmitRemoving flake from the test where a page is reloaded after form submission
Using Day.js instead of Moment.jsUsing day.js library instead of the deprecated Cypress.moment

Network stubbing and spying

RecipeDescription
Stubbing using cy.interceptControl network using cy.intercept API

JS-level stubbing and spying

RecipeDescription
Stubbing FunctionsUse cy.spy() and cy.stub() to test function calls
Stubbing window.fetchWork around the window.fetch limitation
Stubbing window.open and console.logUse cy.stub() and cy.spy() to test application behavior
Stubbing window.printUse cy.stub() to test window.print call made from the application
Stubbing Google AnalyticsUse cy.stub() or cy.intercept() to test Google Analytics calls
Spying and stubbing methods on console objectUse cy.spy() and cy.stub() on console.log
Stub resource loadingUse MutationObserver to stub resource loading like img tags
Stub navigator.cookieEnabled propertyUse cy.stub() to mock the navigator.cookieEnabled property

Unit Testing

RecipeDescription
Application CodeImport and test your own application code

Note: looking for the React/Vue component testing recipes? Read the Introducing the Cypress Component Test Runner– new in 7.0.0 blog post.

Server Communication

RecipeDescription
Bootstrapping your AppSeed your application with test data
Seeding your Database in NodeSeed your database with test data
XHR assertionsSpy and assert on application's network calls
Visiting 2nd domainVisiting two different domains from two different tests and passing value from one test to another
Pass value between specsPass a value from spec to spec via the setupNodeEvents function in the Cypress configuration using cy.task
Stream test resultsStreams each test result from the browser to the setupNodeEvents function to an external process via IPC
OfflineTest web application when the network is offline
Server timingReport server timing results from Cypress test
Wait for APICall the backend using cy.request until it responds
Making HTTP requestsHow to use cy.request, window.fetch, and cy.task commands to make HTTP requests to the server with and without cookies

Other Cypress Recipes

RecipeDescription
Visual TestingOfficial Cypress guide to visual testing
Code CoverageOfficial Cypress guide to code coverage
detect-page-reloadHow to detect from Cypress test when a page reloads using object property assertions
run in DockerRun Cypress with a single Docker command
SSR E2EEnd-to-end Testing for Server-Side Rendered Pages
Using TS aliasesUsing TypeScript aliases in Cypress tests
stub-navigator-apiStub navigator API in end-to-end tests
Readable Cypress.io testsHow to write readable tests using custom commands and custom Chai assertions
Parallel or notRun Cypress in parallel mode on CircleCI depending on environment variables
Use TypeScript With CypressStep by step tutorial on how to set up TypeScript support in Cypress using WebPack bundler
Cypress should callbackExamples of .should(cb) assertions
Cypress jumpCreate a React component using JSX and inject it into live application from a Cypress test
Unit testing Vuex data store using Cypress.io Test RunnerComplete walkthrough for anyone trying to unit test a data store
Triple Tested Static SiteHow to test static sites three times before and after deployment to GitHub pages

Community Recipes

RecipeDescription
Visual Regression TestingAdding visual regression testing to Cypress
Code coverageCypress with Coverage reports
CucumberExample usage of Cypress with Cucumber
JestExample for the jest-runner-cypress
MailosaurUtilizes cy.request() or cy.task() with mailosaur to test emails sent with sendmail
Chat AppTest a Socket.io Chat App using Cypress
Email TestingFull Testing of HTML Emails using SendGrid and Ethereal Accounts

Overview

Installation

## install all dependencies from the root directory
npm install

Opening Cypress App

cd ./examples/testing-dom__drag-drop
# start local server
npm start &
# open Cypress App
npm run cypress:open

Running from the CLI

Same as running Cypress GUI but with cypress run command (and any CLI arguments)

cd ./examples/testing-dom__drag-drop
# start local server
npm start &
# run Cypress tests headlessly
npm run cypress:run

### runs all example projects in specific browser
### similar to cypress run --browser <name>
npm run cypress:run -- --browser chrome

### sends test results, videos, screenshots
### to Cypress dashboard
npm run cypress:run -- --record

You can find the recording at the Cypress Dashboard linked below

Cypress Dashboard

Development

See Development.md