Set "Puppeteer_Skip_Chromium_Download" Env Variable To Skip Download.
- Read the docs
- Run Cypress on your ain CI
- Record success and failure videos
- Move common code into utility package
- Separate tests into bundles
- Brand JavaScript crashes useful
- Apply examination names when creating data
- Get test condition
- Explore the environment
- Run all spec files locally
- Get command log on failure
- Wait on the right thing
- Write and read files
- Read JSON files with retries
- Conditional logic
- Customize Cypress examination runner colors
- Shorten assertions
- Disable ServiceWorker
- Alternative: delete from each window object
- Control
navigator.language
- Employ fixtures to stub network requests
- Use code coverage
- Use visual testing
- Interactive and headed mode
- Produce high quality video recording
- Use the page base url
- Laissez passer the environment variables correctly
- Parse and utilise URL
- Deal with
target=_blank
- Deal with
window.open up
- Bargain with
window.location.replace
- Minimize memory use
- Kickoff browser with specific time zone
- Scaffold the new projects faster
- Install Chromium via Puppeteer
- Create aliases before each test
- Hover control
- Wait for data
- Make HTTP requests
- Restart the tests
- Expect for network idle
- Check if the network call has not been made
- Observe good Cypress examples
- Use cy.log to print to the Command Log
- Log mistake before throwing it
- Use a single cy.contains control
- Disable Save Credit Menu prompt
- Turning the credit card salvage prompt off by changing the placeholder text
- Turning the credit card salvage prompt off past using autocomplete off
- Print timestamp with the mistake message
- Add a custom delay command for better videos
- Visit the blank page to stop the running app
- Do non load pesky 3rd political party script
- Bargain with blazon module
- Access a MySQL database
- Prepare Create-React-App ESLint warnings
- Use Lodash
- Detect when the document reloads
- Fourth dimension function of the test
- Departure between cy and Cypress globals
- Compare ii loaded files
- See besides
- Related posts
We have been successfully using Cypress to verify our websites and web apps for a while. Here are some tips & tricks we have learned.
Even this blog is tested using Cypress :)
Read the docs
Cypress has splendid documentation at https://docs.cypress.io/, including examples, guides, videos and even a busy Gitter conversation channel. There is likewise "Search" box that quickly finds relevant documents. The search is really good and covers the docs, the weblog posts and the examples.
Recently common recipes were combined into a single place. If you still have an result with Cypress, please search through open up and airtight bug.
You can also read my other blog posts about Cypress nether tags/cypress.
Run Cypress on your own CI
As long as the projection has a projection key, you tin can run the tests on your ain CI boxes. I institute running within Docker to be the easiest, and even built an unofficial Docker image with all dependencies.
Annotation that cypress ci ...
will upload recorded videos and screenshots (if capturing them is enabled) to the Cypress cloud, while cypress run ...
will not.
Record success and failure videos
When Cypress team has released the video capture characteristic in version 0.17.11 it speedily became my favorite. I have configured our GitLab CI to go along artifacts from failed test runs for 1 calendar week, while keeping videos from successful test runs only for a iii days.
ane | artifacts: |
Whenever a examination fails, I lookout the failure video next with the video from the last successful test run. The differences in the subject nether test are quickly obvious.
Movement mutual code into utility parcel
Testing lawmaking should be engineered as well as the product code. To avoid duplicating testing helper utilities, nosotros advise to move all common helpers into their own NPM module. For example, we use local CSS styles with randomized class names in our web code.
1 | <div class="table-1b4a2 people-5ee98"> |
This makes the selectors very long since we need to use prefixes.
1 | cy.get('[class*=people-]') |
By creating a tiny helper function nosotros alleviated the selector head aches.
one | import {classPrefix} from '@team/cypress-utils/css-names' |
The exam lawmaking became a lot more than readable.
Split tests into bundles
Using a single cypress/integration/spec.js
file to examination a large web application quickly becomes difficult and time consuming. We have separated our code into multiple files. Additionally, we keep the source files in src
folder and build the multiple bundles in cypress/integration
using kensho/multi-cypress tool.
The multi-cypress
tool assumes that Docker and GitLab CI are used to really run the tests. Each test will exist inside its own "exam job", thus 10 spec files can exist executed at in one case (assuming at least x GitLab CI runners are available).
The command to run a specific spec file is cypress run --spec "spec/filename.js"
by the way.
Make JavaScript crashes useful
As I take said before, the truthful value of a exam is non when it passes, but when it fails. Additionally, even a passing test might generate client-side errors that are not crashes and do not neglect the test. For example, we often use Sentry exception monitoring service where we forrad all client-side errors.
If a client-side error happens while the E2E Cypress test is running, we need this additional context: which test is executing, what steps were already finished before the fault was reported, etc.
Past loading a small library send-exam-info before each test, we can capture the name of the examination, its spec filename and fifty-fifty the Cypress exam log every bit breadcrumbs; this information is then sent to Sentinel with each crash. For example, the exception below shows the name of the test when the fault was reported
Similarly, the Cypress examination steps are logged as breadcrumbs and are sent with the exception assuasive any developer to quickly get a sense when the fault happens as the test runs.
Employ test names when creating data
Often equally part of the E2E test we create items / users / posts. I like to put the total exam title in the created data to easily meet what test created which datum. Within the test we can quickly take hold of the full title (which includes the full parent's title and the current test proper noun) from the context.
I also like creating random numbers for additional departure
ane | const uuid = () => Cypress._.random(0, 1e6) |
Get test status
If yous use function () {}
as the test'south body, or a torso of a hook, you tin can find lots of interesting backdrop in the this
object. For instance, you can see the country of the test: passed or failed. To see them all, place the debugger
keyword and run the test with DevTools open.
1 | afterEach( office () { |
There is an object for the unabridged test, and for the current hook
The this.currentTest
object contains the status of the entire exam
Explore the environment
You tin pause the exam execution past using debugger
keyword. Brand sure the DevTools are open!
1 | it('bar', function () { |
Run all spec files locally
If you separate Cypress E2E tests into multiple spec files, you soon terminate up with lots of files. If yous need to run the scripts one past 1 from the control line, I wrote a small utility run-each-cypress-spec.
i | npm install -g run-each-cypress-spec |
If you need environment variables (similar urls, passwords), you lot can hands inject them using as-a
1 | as-a cy run-specs |
Get command log on failure
While videos of the failed tests are useful, sometimes we just want to get a sense of the failure before triaging it. In the headless CI style, you lot can become a JSON file for each failed exam with the log of all commands. See the JSON file below as an example of a failed exam and the file it generated.
1 | { |
This is a split projection that just needs to exist included from your cypress/support/alphabetize.js
file. For instructions see cypress-failed-log projection.
Wait on the right thing
Information technology is of import to wait for the right element. Imagine we have a listing of items in the DOM. We expect a new element to appear with text "Hullo". Nosotros could select first the list, then the element containing "Hi" and check if it becomes visible
one | cy.get('.listing') |
Simply sometimes it does not work. When we cy.get('.list')
Cypress saves the DOM element as the "subject" and then tries to wait for a child of that chemical element with text "How-do-you-do" to become visible. If we utilise React for case, the DOM of the list might be recreated from scratch if nosotros push a new item into the list. When that happens Cypress notices that the "subject" DOM it holds a reference to becomes "discrete from the DOM" - it becomes an orphan!
A improve solution to this problem is to utilize a composite CSS selector that will grab the list AND the particular in a single operation.
1 | cy.contains('.listing li', 'Hi') |
This forces Cypress to wait for the listing AND listing item element without caching a reference to the DOM element .list
.
You can use advanced CSS selectors to get an element in a single control. For example instead of cy.get('.something').outset()
you lot could utilise cy.get('.something:outset-child')
. Similarly,
1 |
|
Write and read files
Y'all tin can write files to deejay direct from Cypress using cy.writeFile and read an existing file using cy.readFile. What if you want to read a file that might not be? cy.readFile
will fail the examination if file does not exist, thus we demand to detect a work around.
In my case, the file I would like to load is a JSON of test values useful for Jest-like snapshot testing.
Here is a cracking flim-flam. Salve the file using cy.writeFile
, for example cy.writeFile('spanshots.json')
whenever there is something to save. When reading the file, fetch it through the Cypress code proxy using fetch
Notice how the test spec itself is served by Cypress from URL which looks like http://localhost:49829/__cypress/tests?p=cypress/integration/spec.js-438
. Allow usa "hack" it to load a file that might not exist.
The lawmaking below tries to load snapshots file before each test. If the fetch
phone call fails, the file does not be.
1 | permit snapshots |
If the fetch
call succeeds, the returned text
will Non be original JSON! Instead information technology volition be webpacked module :)
For instance, here is the saved file
one | { |
Here is how born Cypress bundler returns it in response to /__cypress/tests?p=./snapshots.json
- I take shortened the webpack boilerplate preamble.
1 | ( office e(t,n,r){ part ...)({ane:[function(crave,module,exports){ |
Notice that our JSON has been placed into module with id 'one' (first line expression {1:
). The entire bundle registers a stand alone require
function. If nosotros want to get into the actual "module" contents we have to do the following in our function loadedText(text)
to terminate the hack
one | part loadedText (text) { |
Nail, the object snapshots
has been loaded from the file snapshots.json
which might or might not be.
Notation while I have successfully used the above hack when running Cypress locally, it was always declining when doing cypress run
in headless mode.
Read JSON files with retries
Cypress cy.readFile command automatically parses JSON files. It also re-reads the file if the assertions on the returned JSON neglect. For example, let'southward validate the number of items stored by the app in its JSON "database" file:
1 |
|
Fifty-fifty if the awarding sends the items after a time filibuster, the cy.readFile(...).should(cb)
combination retries and successfully passes when all four items are institute.
Conditional logic
Sometimes you might need to collaborate with a folio element that does not always exist. For instance there might a modal dialog the showtime fourth dimension you use the website. You want to close the modal dialog.
one | cy.become('.greeting') |
Only the modal is non shown the second time around and the to a higher place code will fail. In social club to check if an element exists without asserting it, use the proxied jQuery function Cypress.$
1 | const $el = Cypress.$('.greeting') |
The to a higher place cheque is safe.
Customize Cypress test runner colors
Read Cypress Halloween Theme and bank check out cypress-dark plugin.
Shorten assertions
For cy.location
you tin can laissez passer the part yous are interested in
1 | cy.location().should( location => { |
is the same as
1 | cy.location('pathname').should('equal', '/todos') |
You can use its
to become nested properties easier
ane | cy.go('@login').should( req => { |
is the same every bit
one | cy.get('@login').its('response.trunk.accessToken') |
and this could exist expressed more conspicuously in steps
1 | cy.then(() => { |
You tin can expect for network request to happen and then check something using cy.then
one |
|
Instead we can use .so
later on waiting for the network request. It is besides helpful to print the message when checking for the token, otherwise command log simply says "look nix to equal null".
1 | cy.await('@login') |
You don't need to wrap elements just to dynamically employ them. For example if you lot want to test each detail from the list
one | const inputs = [ |
Every Cypress command is automatically inserted into the queue, so yous can iterate over the items and utilize Cypress commands, everything will be queued correctly.
1 | inputs.forEach( input => { |
I prefer cy.offset()
to cy.eq(0)
.
Disable ServiceWorker
ServiceWorkers are great - but they can really impact your end-to-end tests past introducing caching and coupling tests. If you want to disable the service worker caching you need to remove or delete navigator.ServiceWorker
when visiting the folio with cy.visit
.
Beginning, here is the mode that does not work - simply deleting the belongings from the navigator
object.
1 | it('disables it', function () { |
The reason for this is that we are deleting the holding from the wrong object. The ServiceWorker
is NOT divers on the navigator
, it is defined on its prototype. You can confirm this by using Object.getOwnPropertyDescriptor
method:
one | Object.getOwnPropertyDescriptor(win.navigator, 'ServiceWorker') |
Afterward we delete the property from the correct object, the application code will no longer recollect it can annals the service worker.
1 | it('disables it', office () { |
one | <body> |
Annotation: once deleted, the SW stays deleted in the window, even if the application navigates to another URL.
Alternative: delete from each window object
Y'all can register an issue handler to fire on every window load issue, where you can remove the ServiceWorker
ane | Cypress.on('window:earlier:load', (win) => { |
Read also "Stub navigator API in cease-to-stop tests" for another example.
Imagine you take a page that shows different greeting depending on the navigator.linguistic communication
property.
ane | <body> |
How do we check if the default English greeting is displayed? Easily
1 | information technology('shows default greeting', () => { |
But how practise we force the Klingon greeting to exist displayed? Trying to change read-merely navigator.language
holding throws an error.
ane | it('shows Klingon greeting', () => { |
The navigator.language
holding is actually gear up on navigator.__proto__
object:
1 | Object.getOwnPropertyDescriptor(navigator, 'language') |
Nosotros can create language
holding on the navigator
object instead - thank you, prototypical inheritance! We tin specify the belongings's value:
i | it('shows Klingon greeting', () => { |
This test shows proper respect to each Klingon warrior browsing the spider web.
How practice nosotros ensure that the awarding actually read navigator.language
belongings when displaying the greeting? Maybe the "nuqneH" is hard-coded! We demand to runway navigator.language
"go" access. Nosotros can exercise this using cy.stub
method.
1 | it('checks if awarding gets language holding', () => { |
Now nosotros know for sure how the application behaves.
Use fixtures to stub network requests
If your tests are full of stubbed network responses, motility the responses into fixtures
before
1 | information technology('does A', () => { |
after 1
i | it('does A', () => { |
after two
You tin fifty-fifty require the JSON fixtures directly if the 2d response is simply a petty bit different from the first response
one | const responseFixture = require('../fixtures/first_query_response') |
See cy.route and cy.fixture documentation.
Bonus: read Import Cypress fixtures
Utilise code coverage
Yous tin can instrument your application and employ Cypress code coverage plugin to produce combined reports in multiple formats. Terminate-to-end tests are very effective at covering a lot of lawmaking in a single exam.
- Combined Stop-to-end and Unit of measurement Test Coverage
Use visual testing
If a test grows to be very long because information technology checks so many elements on the page, see if information technology makes sense to test the entire page using Visual Testing.
before
1 | it('checks lots of things', () => { |
afterwards
1 | it('checks lots of things', () => { |
Bonus: check out bahmutov/sudoku for visual component testing using open source tools, and read Visual testing for React components using open source tools.
Interactive and headed mode
You can notice out if the test is currently running using the interactive mode which is when the user calls cypress open
.
1 | if (Cypress.config('isInteractive')) { |
When you use the interactive mode yous always see the browser, thus the browser is always headed. But when using the cypress run
command, the browser might exist headless or headed. You tin find out how the browser is displayed:
1 | if (Cypress.browser.isHeaded) { |
When using cypress run
, Electron is headless by default, while Chrome and Firefox browsers are headed by default. You can control the browser though:
1 | npx cypress run --browser chrome --headless |
Trying to pass both --headed
and --headless
CLI parameters raises an mistake.
Produce high quality video recording
Read the full blog mail Generate High-Resolution Videos and Screenshots.
You can detect well-nigh of the advice below implemented in bahmutov/cypress-picture. To generate better videos from tests
- set up video compression to false
- ready browser window size to larger value, which should work fine when using headless Chrome on CI
1 |
|
- hide command log
Yous can "expand" the application under test iframe to embrace the entire window
one | const clearViewport = () => { |
Call this function before the tests.
- utilize native Chrome Debugger Protocol to take full folio screenshots. See "cypress-picture" project.
Utilise the page base of operations url
Sometimes multiple tests visit a different base url. For example, you might normally get to the index page by setting baseUrl
in the config file
one | { |
Every test can cy.visit('/')
and get to the alphabetize folio. Only imagine that a suite of tests is trying to visit and test the "Near" page. It is located at /about.html
, and then every test has to visit it.
ane | describe('About', () => { |
Now, we tin refactor the tests to avoid duplication. For example, we could movement the cy.visit
into beforeEach
claw.
1 |
|
Works.
Or nosotros could create a utility function:
1 | describe('About', () => { |
It works as well.
Hither is one more way to (corruption) test configuration feature introduced in Cypress v5.0.0. We volition alter the baseUrl
in the describe
block to apply to merely these tests.
1 | describe('Virtually', { baseUrl: '/about.html' }, () => { |
Detect the { baseUrl: '/near.html' }
parameter in describe
call. Nosotros can overwrite multiple config values using this parameter. In our case, we overwrite the baseUrl
, appending the file name. In the cy.visit('')
call we pass an empty string - because nosotros exercise non want to suspend /
at the end.
Merely the tests fail.
While our visit used an empty cord, Cypress requires baseUrl
to exist a valid base URL and appends /
at the end automatically.
Luckily, Cypress v5.iv.0 has a fix for baseUrl
that has params for outcome #2101. If your base of operations url is of the grade ...?foo=bar
then visiting ''
would keep the original full url. Permit's modify our test by appending ?
to the base url:
1 | - describe('Nearly', { baseUrl: '/about.html' }, () => { |
Now the tests pass - and the ?/
at the end of the URL is ignored
Pass the environment variables correctly
Imagine you demand to pass database username and password from your test. These values are probably available as surroundings variables. How would y'all pass them to cypress run
? You lot might try something like this in the bundle.json
file. It volition NOT work:
1 | { |
Starting time, you do not need the node_modules\\.bin
path when calling an NPM alias - they are automatically resolved past the npm run
command. Thus ever use simply:
ane | { |
The above control will Non work still. To see why, change the cypress run
to cypress open
to see the Cypress GUI.
i | { |
Select the "Settings" tab and inspect the resolved surround variables.
We have two problems:
- Instead of passing the environment variable'due south value, nosotros got the strings "$DB_USERNAME" and "$Password". Resolving surround variables within commands might exist catchy and depend on the operating system.
- The username and the password are stored under names
db.user
anddb.password
, which might be not what you expect. From the dot notation, I would expect these values to create an objectdb
with propertiesuser
andcountersign
.
But there are other trickier problems here. Let'south change our NPM scripts to avoid single quotes around the values. Nosotros hope that now the environment variables are resolved correctly.
1 | { |
At first, information technology appears to work
Now, allow's try a user name with a space.
Ummm. The infinite inside the username value created bug; the cypress open
command finer received ended with --env db.user=joe smith,db.password=123
. The part after --env db.user=joe
was ignored!
Solution: Cypress can grab the surround variables in multiple means. The well-nigh powerful and flexible way is to grab them from the process.env
object using the plugins code.
ane | module.exports = (on, config) => { |
The plugins file runs in Node environment, has access to the process.env
object. It tin can catch the variables, check their values, and identify them into a single object db
. Now the Settings tab shows the right values.
Additional reading: the blog post Go along passwords secret in E2E tests and the recipe Environs variables.
Tip: when working locally you can use the utility every bit-a to conveniently inject environment variables when running any control.
Parse and use URL
Permit's accept a Adjacent.js application with dynamic routes. We can scaffold one using the provided example.
You can notice the complete source code at bahmutov/dynamic-routing-app
The app was initialized using the provided example command
ane | npx create-next-app --case dynamic-routing dynamic-routing-app |
The app contains two dynamic routes:
-
pages/post/[id]/index.js
- e.one thousand. matches
/mail/my-example
(/mail service/:id
)
- e.one thousand. matches
-
pages/post/[id]/[comment].js
- eastward.thou. matches
/post/my-example/a-comment
(/post/:id/:comment
)
- eastward.thou. matches
Let's run into how we can parse the above URLs to use them during tests. First we need to install Cypress and start-server-and-test:
I can scaffold the Cypress files with my helper bahmutov/cly
ane | npx @bahmutov/cly init |
We place the base url localhost:3000
in cypress.json
file and starting time the app and Cypress. Our offset test tin confirm the home page loads:
1 | describe('Dynamic routes', () => { |
Bang-up, we can make sure the link "Nearly" goes to the "Most" folio.
1 | it('goes to the about folio', () => { |
The test passes, simply with a tiny red flag. Find piffling eye crossed icons side by side to the "contains" command?
The Next.js application fetches a static HTML with the markup present but invisible. It is hydrated later - but nosotros desire to click on the link similar a real user would, after it becomes visible. Let's add an assertion.
1 | it('goes to the well-nigh page', () => { |
Much meliorate.
We assert that nosotros go to the correct folio by using the expression cy.url().should('match', /\/well-nigh$/)
. It works, but the command cy.url returns the full URL. If you lot click on the control yous will encounter what information technology yields:
Nosotros are interested only in the relative pathname - the /about
part. Thus I suggest using cy.location command that parses the URL and tin can yield only the interesting part.
Now let'south bank check the first post. We can outset with the same exam as earlier
one | it('goes to the first post', () => { |
At present permit's get to the first command. Nosotros need to click on the link, but before we do this, allow's validate it. Let'due south grab the current post url and use it somehow in our tests.
i | it('goes to the showtime comment', () => { |
Later on the assertion .should('include', '/mail')
passes, the value is yielded to the next command where we print it.
Now we have all the JavaScript magic we need to parse and piece URL. Allow'due south even modify the test and go to the 2nd comment of the kickoff post.
1 | it('goes to the first post / second comment', () => { |
We can parse, validate, and use the URL in our test.
Deal with target=_blank
Imagine a link on the page uses <a href="/about.html" target="_blank">About</a>
. Cypress does not piece of work with the second tab, and so what can we do?
one | information technology('loads the about page', () => { |
Figure out what you desire to test. You can for example verify the link has the expected address and aspect target=_blank
and call it a day.
1 | it('loads the about page', () => { |
We can also change the target attribute earlier clicking the link (but after confirming information technology to be blank). And then we tin verify the second "tab" loads correctly.
1 | it('loads the about folio', () => { |
Bargain with window.open up
Imagine the awarding under test uses window.open up()
to load a new URL in the second tab.
i | <a href="/most.html" target="_blank">Virtually</a> |
Past default the /virtually.html
page opens in a new tab - and nosotros do non want that. Let's stub the window.open
method instead.
ane | it('opens the about page', () => { |
If we really want to load the new URL, let'southward call the original window.open
method, passing _self
as the second parameter.
Tip: use <method>.wrappedMethod
to get to the original method wrapped in Sinon stub. When nosotros call cy.stub(win, 'open')
it replaces win.open up
method with a Sinon stub function. If we desire to call the real win.open up
method, we tin can use the reference to the saved original part: the win.open up.wrappedMethod
is the original unstubbed win.open up
method.
i | it('opens the about page', () => { |
See also: the post Stub window.open and video cy.stub: stub a method on the window object
Deal with window.location.supersede
Imagine, our index.html
does the following:
1 | <trunk> |
The redirect causes problems, as we cannot admission the new origin from the examination. We cannot simply stub the location.supervene upon
method - this property (and pretty much every belongings on the location
object) is locked downwards; it is neither writable, nor configurable.
Thus we cannot apply cy.stub(win.location, 'supersede')
. We cannot supervene upon window.location
property either - considering it also is locked down. Instead we need to modify our application's code to avoid using the window.location.supersede
method completely.
During the test, we tin utilise the cy.intercept command to modify the application lawmaking. For instance, it could telephone call window.__location.supplant
instead. Our exam would create this dummy window.__location
object earlier the application loads.
1 |
|
The test runs and passes. Notice in that location is no redirect, and our stub and intercept were called.
You tin can inspect the certificate the browser receives afterward the intercept replaced the window.location
with window.__location
string. The replacement happens at the proxy level, before the response is sent to the browser. See the presentation How cy.intercept works for details.
You can watch the above caption in this video
Minimize memory use
Sometimes Cypress can crash during CI run due to running out of retentivity. Typically it shows a message like this:
ane | 10:38:58 AM: We detected that the Chromium Renderer procedure just crashed. |
You can contour memory usage every 2nd with environment variables
one | export DEBUG=cypress:server:util:process_profiler |
The things you can do to minimize the amount of memory used:
- try running tests without extra reporters, plugins, and preprocessors
- split specs to have fewer tests per spec. Cypress opens and closes the browser for every spec
- turn the video recording off with
video: false
usingcypress.json
or surround variables - plow the command log off using the environment variable
CYPRESS_NO_COMMAND_LOG=one
- expose garbage collection and running it subsequently each test. Come across issue 8525, but in general for Electron browser you want to apply an environment variable
ELECTRON_EXTRA_LAUNCH_ARGS=--js-flags=--expose_gc
and from the test callwindow.gc()
method if available
1 | afterEach(() => { |
Tip: if Electron keeps crushing, try running tests using Chrome or Firefox browsers.
Get-go browser with specific time zone
Y'all can outset Cypress (and thus the browser information technology spawns) with specific time zone to meet how the application handles information technology.
1 | $ <timezone> npx cypress open |
Typical time zones are America/New_York
, Europe/Berlin
, Europe/London
, Asia/Tokyo
.
Tip: an application tin can obtain its time zone using the following code snippet
1 | Intl.DateTimeFormat().resolvedOptions().timeZone |
For more information, read Testing Time Zones in Parallel
Scaffold the new projects faster
Past default every new projection scaffolds case specs when you run cypress open
for the very start time. I have written an utility @bahmutov/cly to scaffold a sample project without opening Cypress and and so deleting the many scaffolded spec files.
Yous yet need to install Cypress equally a dev dependency starting time, only then y'all can do
1 | npm i -D cypress |
Y'all tin scaffold a TypeScript or a bare-bones projects
i | # adds appropriate tsconfig.json |
Watch me scaffolding new projects in the video below
Install Chromium via Puppeteer
Sometimes the CI machine you lot want to run tests on does non take Chrome installed, merely you really desire to use it to run your tests. For example, Chrome is more stable and crashes less often than Electron. If you cannot install Chrome browser using "normal" commands, you can install Chromium past installing Puppeteer NPM dependency.
1 | npm i -D puppeteer |
From the plugin file we can observe the browser and insert it into the list of other arrangement browsers discovered by Cypress.
1 | const puppeteer = require('puppeteer') |
Open Cypress and you lot should meet "Chromium" in the drop down list of browsers.
Tip: if you have problems with Cypress browser detection, run it with DEBUG=cypress:server:browsers
environs variable.
To pick the Chromium browser in headless mode use the control:
i | npx cypress run --browser chromium --headless |
See my example project cypress-chromium-via-puppeteer-example.
Tip: if yous need to skip installing Puppeteer in some circumstances, apply the environment variable PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
. I utilize this variable on some CIs to avoid waiting for the Chromium to download if I do not plan to run E2E tests in Chromium.
Create aliases earlier each test
If you lot create aliases using .every bit command, remember that aliases are reset before each test. Thus y'all cannot create them in the before
hook and use from the second test:
ane | before(() => { |
Instead, create the aliases using beforeEach
hook
ane | beforeEach(() => { |
Hover control
Meet bahmutov/cy-hover-example for links.
Wait for data
Tip: come across the tested case at cypress-examples "Wait for data" recipe
Imagine we have a variable that after will receive some data. How do we retry the check from the test? Imagine we are waiting for a specific network request, and once it arrives it saves the list sent by the awarding.
Let me bear witness you what will not piece of work:
1 | let listing |
The above code does not work because the expect(list).to.be.an('array')
runs earlier the cy.get('#post-list').click()
executes. The expect
is immediate, while cy.get
is chained and delayed.
You might delay checking the list
by moving it into .and then
callback to be executed after the .click()
command:
1 | let list |
The in a higher place code is slightly more than right, but is still wrong. It will bank check the value of the list
variable After clicking on the push, but without car-retries, it will only check once. What are the chances that the cy.intercept
worked past then? Pretty much nil.
We need to retry checking the list
, which we can do by changing the .then
to .should
command. The .should(cb)
is retried automatically. Thus our showtime solution is to use the cy.should(callback)
command:
i | let listing |
You can see the solution working in the recording below, where the awarding requests the data subsequently about i.3 second delay.
We can ameliorate this solution a footling scrap past using cy.wrap control. We can wrap a reference to an object, and the intercept volition set up a property inside that object. This "trick" allows us to use implicit assertions completely bypassing the need for ".so" callbacks.
1 |
|
Brand HTTP requests
Read Cypress asking and cookies
Restart the tests
You lot can programmatically click the "Re-run" tests button from code to restart the tests
1 | window.meridian.document.querySelector('.reporter .restart').click() |
Come across cypress-grep and cypress-picket-and-reload examples.
Expect for network idle
Cypress is simply JavaScript, and with the new cy.intercept you tin can implement your own "wait for the network to be idle for Due north seconds" characteristic.
1 | information technology('waits for network to exist idle for 1 second', () => { |
I take moved the above helper into a plugin cypress-network-idle. The above exam could be written as:
ane | cy.waitForNetworkIdle(1000) |
Lookout man the videos introduction to Cypress-network-idle plugin and Ready Intercept And Wait Using cypress-network-idle Plugin.
Cheque if the network call has not been made
Here is a test that confirms a specific network call is Not fabricated until the application adds a new detail.
one | it('does not make Post /todos request on load', () => { |
Find practiced Cypress examples
You can find good Cypress example repositories by searching GitHub using topic cypress-case
and user bahmutov
1 | github.com: topic:cypress-case user:bahmutov |
Here is directly link to the results.
Similarly, yous tin can search for this topic under organisation name cypress-io
one | github.com: topic:cypress-example user:cypress-io |
Here is the direct link to the results.
Use cy.log to print to the Command Log
You tin print the output of a command or a chore using the cy.log control. For example, lets print the object yielded from a task
i | cy.job('getImageResolution', 'test-smile.png').then(cy.log) |
If the object is big, cy.log
shortens it and just prints Object{N}
where N
is the number of properties. We can print the unabridged object by passing it through a JSON.stringify
method first.
one | cy.task('getImageResolution', 'test-smile.png') |
Because cy.log
returns void, it does not change the current discipline, and yields its statement to the next Cypress command.
1 | cy.task('getImageResolution', 'examination-smile.png') |
Y'all tin watch this example in this short video
Log fault before throwing it
If you are making a asking and desire to log the possible errors, use .then
+ cy.log
combination before an assertion.
one | cy.asking({ ... }) |
Apply a single cy.contains command
Instead of using cy.get(selector).contains(text).should('be')
concatenation, you lot can only apply
1 | cy.contains(selector, text) |
- The assertion
should('exist')
is already built into cy.contains command - The unmarried command volition be retried until the text appears or the command times out
Watch this short video to see the single command in action.
Disable Salve Credit Card prompt
Sometimes when you fill a credit menu course during the examination, the Chrome browser asks if yous want to save the credit card numbers.
Note: I have taken the credit menu example from this case and ran it locally.
In club to stop Chrome browser from ever asking to store payment methods, y'all could navigate to the special chrome://settings/payments
URL and flip the switch:
Unfortunately, I could non find an equivalent Chrome command line switch to plough it off when launching the browser. Thus I needed another way.
Turning the credit card salve prompt off past changing the placeholder text
In my item example I institute that the browser did non show the "Relieve Credit Card" prompt if the place holder text did not include "credit" or "number" words.
1 | # shows the card salve prompt |
Unfortunately, you lot could not modify the placeholder attribute afterward the page has loaded. The test code below did not work:
1 |
|
Thus I have alter the application'southward HTML values.
Turning the credit card salvage prompt off by using autocomplete off
In another credit carte form example, I was able to successfully turn off the credit card save prompt by adding an attribute autocomplete=off
on the form chemical element itself.
1 |
|
Effort information technology - it might work for you.
Impress timestamp with the error message
Past default a failed test merely prints the error bulletin. You might desire to have the timestamp to meliorate debug the failure. The way to practice this is to modify the mistake message in the failure upshot handler. This is what I have done in Cypress v8:
i |
|
I am using the Cypress.on
method instead of cy.on
to make the handler apply to every examination. Here is the failing test
1 | const f = { |
Hither is the last output
1 | 1) prints error with timestamp: |
Add a custom delay command for meliorate videos
I ofttimes use the custom delay
command to make the recorded test videos clear. Cypress runs pretty fast, and sometimes it is hard to empathise from the video what exactly has happening. So I oftentimes add a 1 2d delay before clicking a button or checking a box.
1 | cy.get('button#submit') |
I extracted the .wait(m, { log: false })
into a custom command delay
.
one | const filibuster = (subject, ms = chiliad ) => { |
The above control tin can be used in a chain or as a stand-alone parent command.
Visit the blank page to stop the running app
Run into the web log post Visit The Blank Page Betwixt Cypress Tests.
Practise not load pesky tertiary party script
Sometimes 3rd party scripts throw random errors when the page is irresolute quickly. In that case, stub the resource with an empty cord.
1 |
|
Deal with type module
If the project uses ES6 modules by specifying in the package.json
"blazon": "module"
, this could cause issues for loading the Cypress plugin file. In that case, create a dummy package.json
in the cypress
folder. Specify the CommonJS blazon and Node will resolve the plugin file again.
1 | { |
See the example in bahmutov/verify-code-example.
Admission a MySQL database
The test runner could admission a database during the test to read some information. For case, the weblog post How To Verify Phone Number During Tests Part two describes how to query a MySQL database to read the phone number verification lawmaking and inbound it into the spider web application course.
Fix Create-React-App ESLint warnings
When creating a new application using Create-React-App, you lot volition run across ESLint warnings - because it does non know almost the Cypress globals like cy
and Cypress
.
To gear up, install Cypress ESLint plugin and add together the recommended settings to the bundle.json
one | { |
For more than details, run into How to configure Prettier and VSCode.
Use Lodash
The super useful Lodash library is bundled with Cypress under Cypress._
belongings. Thus you do not demand to install information technology or even import information technology from the spec file.
one | - import _ from 'lodash' |
If you lot need Lodash methods in your plugin file, you will need to install and require it, though.
Discover when the document reloads
If the page submits a class, or navigates, sometimes the test needs to expect for the new certificate to load. To accomplish this, we tin can compare the certificate
reference earlier the navigation and after.
1 |
|
The to a higher place code works, but the exclamation dumps the document
object into the Cypress Command Log, which takes up a lot of infinite there. Improved version without a very long assertion in the Command Log can use assert
part.
1 |
|
Fourth dimension function of the test
You can fourth dimension how long part of a exam takes, or even an individual Cypress command. Then you lot tin can add an explicit exclamation nearly the elapsed duration. For example, let's time how long the loading element in the application is visible. Nosotros tin can assert the loading element goes away in less than two seconds:
1 | allow started |
See the full explanation in the video below:
Divergence between cy and Cypress globals
Cypress sets two global objects while running: cy
and Cypress
(if you desire to avert them, use local-cypress module). The cy
object is only valid during the test execution; it tin can just be called inside a exam callback role or inside a hook function (like before
, beforeEach
, afterEach
, and after
). The cy
object schedules commands like cy.visit
, creates spies cy.spy
, and sets aliases using cy.equally
- all these operations only make sense in the context of a examination. If yous endeavor to phone call a cy
method outside the test, Cypress throws an error.
The global Cypress
object has static helper methods. It holds the static data virtually the spec file itself, the operating system, and the examination blazon.
i | Cypress.arch |
The global Cypress
too has the bundled libraries, similar Cypress._
(Lodash), Cypress.$
(jQuery), Cypress.Hope
(Bluebird), and a few others.
Finally, Cypress object has the configuration properties available at any time via Cypress.config method. All other data used during the test tin exist passed and stored in the Cypress.env method. You can call whatsoever Cypress
method anywhere: from a test, outside the test, or even from DevTools panel.
ane |
|
Watch the video Cypress vs cy Difference Explanation.
Compare two loaded files
Permit's say you want to compare two binary files using base of operations 64 encoding. You can use cy.readFile command and pass the file into the side by side stride using cy.then callback
ane | cy.readFile('first.png', 'base64').and then( start => { |
The in a higher place assertion might be verbose because it tries to print the values in the comparison. You can minimize the control log assertion message by throwing an mistake just if the images are not equal
1 | cy.readFile('commencement.png', 'base64').then( starting time => { |
See likewise
- my website cypress.tips
- Writing a Custom Cypress Command and How to Publish Custom Cypress Command on NPM
- Cypress weblog, I accept written a large number of web log posts at that place.
- Notes of Best Practices for writing Cypress tests
- The Hitchhikers Guide to Cypress End-To-End Testing
- Unit testing Vuex information store using Cypress.io Test Runner
- video playlist Cypress Tips & Tricks
- Cypress web log posts by Filip Hric
- NPM Tips and Tricks
- Git Tips And Tricks
- Large Spider web App Evolution
DOWNLOAD HERE
Posted by: doyounithe73.blogspot.com
0 Comments