Change is inevitable. From the changing weather to the world we live in, to the bodies we experience life with! So should Software. Hopefully, your software will change for the better. From new features to bug fixes, the automation we write needs to keep up with upcoming software changes.
One great asset we can rely on in development is the use of feature flags. We can hide what we release until we are ready and confident enough in our work to display it to our intended audience. How can our automated tests be reliable when feature flags are being used? Some changes are so drastic, they can create unintended failures and confuse the development team.
This week, let’s look at how conditional testing can help.
TL;DR
Use an if-else statement to test the presence of existing text for an element.
cy.get("[data-testid='title']")
.invoke("text")
.then((title) => {
cy.log(title);
if (title == "Old Title") {
cy.get("h3").contains("Old Title").should("be.visible");
} else {
cy.get("h3").contains("New Title").should("be.visible");
}
});
Let’s break this down.
cy.get("[data-testid='title']")
First, verify that the data-testid you're using exists in the DOM when the flag is either on or off.
.invoke("text")
Here, we are grabbing the text that exists on the element. Check out the Cypress docs if you’d like more information on .invoke()
.then((title) => {...
Now we’re creating a callback function that will yield the text used in .invoke().
cy.log(title);
cy.log() is your friend. Use it. Or not. Whatever.
if (title === "Old Title") {
cy.get("h3").contains("Old Title").should("be.visible");
} else {
cy.get("h3").contains("New Title").should("be.visible");
}
If/else: Now that Cypress has the current title, it can make a good comparison. If the title is equal to the old title, then the test will pass as expected. If not, the test can still pass as we are expecting the new title to appear.
🗒️ What this isn’t checking: Yes, this has limitations. If the feature flag is on, but the old title is appearing, the test will still pass. Keep this in mind and tweak it as needed when creating tests for your test suite.
When the new changes are out there and all we see are rainbows and unicorns, we can remove the if/else statement:
cy.get("[data-testid='title']")
.invoke("text")
.then((title) => {
cy.get("h3").contains("New Title").should("be.visible");
}
});
Thankfully, there is plenty of documentation when it comes to conditional testing. Please check out the following links from Cypress and the community contributors.
May all your changes be good ones.
Till next time…
Written with HOPE 🔆 Ancestors Pain Healing || 396Hz Root Chakra Frequency Flute & Water Meditation & Sleep Music playing in the background.
Enjoyed this. I can't imagine coding at work without feature flags. They make feature development so much easier.
Also, why does Cypress code remind me of jQuery? 😅 Maybe it's the chaining.