Imagine you have a simple end-to-end test
- visit the page
- find a link and click on it
- confirm the browser goes to the target page
Using Cypress I could write something like this
1 | cy.visit('/') |
What URLs did the test visit? Let's find out.
🎁 You can find the full source code for this blog post in the repo bahmutov/cypress-url-example.
Overwrite cy.visit
We could focus on the pages explicitly visited by the test runner by overwriting the cy.visit command and keeping track of all target urls. We can keep track of URL strings by storing an array in the Cypress.env
object.
1 | Cypress.Commands.overwrite( |
The finished test shows the ['/']
list with a single URL
Our test goes to the /videos.html
URL via the click, not via cy.visit
, and so it is not in the list stored in the Cypress.env('visitedUrls')
array.
We need to store all urls, not just the starting ones.
Cypress events
Cypress has a long list of emitted events the test can subscribe to: uncaught:exception
, window:confirm
, etc. The event url:changed
is the one we want to subscribe to.
1 | beforeEach(() => { |
Now we see the list of the URLs that includes the initial page, followed by the videos page, back to the initial page.
Hmm, the list includes the starting page twice. Let's use a Set instead of an array.
1 | beforeEach(() => { |
Print to the terminal
Let's print the list of collected URLs to the terminal instead of the browser console. I will use my plugin cypress-log-to-term that prints the current subject to the terminal
1 | afterEach(() => { |
Tip: the afterEach
hook executes even if the test fails, so you should always see the list of URLs.
In the terminal you should see the list of strings
1 | ["/","/videos.html"] |
Plus the subject should be reflected in the Command Log
Nice.