Imagine you are testing a web page showing the purchase receipt.
When the user clicks on the "View Summary" button, a dialog pops up showing just the total amount paid
1 | describe('Receipt', () => { |
How would you confirm that the total $ shown in the summary is the same as the total amount shown in the popup dialog?
A typical test would simply grab one amount and check if the second element has the same text
1 | describe('Receipt', () => { |
This is a bad idea. You are using the page as the source of truth. You are trusting the first element to be correct, without verifying it. For example, both elements might not shown any meaningful numbers!
Oops, the two elements show the same meaningless text.
Comparing elements' text is also prone to trip up on formatting and display differences. For example, one element could put the $
character outside its span element.
1 | <!-- the summary row --> |
To the user, both totals are correct. But the test fails.
Instead of trusting the web page to be correct, let the test itself be the source of the ground truth. Stub the data, stub the network call, control the data loaded by the page - any technique is good. Even a little bit of duplication is ok in the testing code as long as the test intention is clear and easy to maintain.
1 | describe('Receipt', () => { |
The test is passing, does not trust the page to show the correct value, and is easier to read, since we avoid using a cy.then
callback - something I always advocated, see the video Good Cypress Test Syntax for example.
Solid.