Recently I noticed a video in a Linkedin post showing a few Cypress tests. The tests confirmed an alert is happening with right text, plus a modal was showing the right text. Here is a screenshot of the original post.
I noticed a few things about those tests that might be improved. Here is my refactoring of each of the three tests.
🎁 You can find the original source code in my repo bahmutov/webdriverSite. You can see the final solution in the branch solution. 📺 You can watch a recording of me refactoring all tests in the video Refactor Cypress Tests Checking Alerts And Modals.
Test one
The first test confirms the application calls the alert(...)
with the right text.
1 | describe('Lidando com Popups e Alerts', () => { |
Above the test I added my notes about what could be improved in this test. We never actually confirm that the application calls alert(...)
. You could comment out the .click()
and the test would still work. Here is the improved test that uses cy.stub command to confirm the app does call alert
with the right text argument.
1 | // need to ensure the alert actually happens |
For more stub examples and checking the alert
behavior, see my stubs examples page.
Test two
1 | it('Modal Popup', () => { |
We can take advantage of cy.contains command to find elements by text. We should also confirm the modal disappears after clicking the "Close" button.
1 | // refactor to use cy.contains command |
Test three
1 | it('Outra maneira para o Modal Popup', () => { |
In the test above we are spying on the network requests, but the spy is too permissive. We can limit it to only spy on the calls to the Google Analytics website. To learn more about network intercepts, see my course Cypress Network Testing Exercises
We can also fix several selectors to be precise. We also need to better check the behavior of the Loader element that first must appear and the go away.
1 | // use a better selector for to click the ajax loader |
For more details, read the blog posts Be Careful With Negative Assertions and Negative Assertions And Missing States. To learn more about testing different application states and confirming the application behaviors, see my course Testing The Swag Store
Tip: have a complex Cypress test you are unhappy with? Is it public? If yes, send it my way, and maybe I will record a video refactoring it to make the spec elegant, precise, and solid.