Have you ever wondered how to dynamically skip a test in cypress based on a condition?
When writing tests, there are times we need to conditionally skip certain test cases based on the environment or other condition. This is particularly useful
- When a feature is unavailable in a specific environment
- If a test isn't relevant to a particular setup.
Instead of manually commenting out tests or using environment variables awkwardly, we can dynamically control test execution using conditional skipping.
I'm gonna walk you through how to conditionally skip tests based on the baseUrl configuration in Cypress. This can be applied to any other condition as you wish too… ❤
The Scenario
Let's say we are running tests in multiple environments, such as:
- Development (dev.yourdomain.com)
- Staging (staging.yourdomain.com)
- Production (yourdomain.com)
Now, we have a test that should run in all environments except the development environment. Instead of hardcoding this condition in multiple places, we can dynamically control whether a test executes or gets skipped.
You might have done this:
This way, the test will be marked as Passed, on the dev environment execution which is WRONG! It should be marked as skipped.
Here's how we achieve that in Cypress the proper way:
Breaking It Down
-
Fetching the
baseUrl
: Cypress allows us to access the test configuration using Cypress.config(). Here, we extract baseUrl to determine which environment we are running in:const baseUrl = Cypress.config('baseUrl');
- Always Running Tests: The first and last tests (should always run and should also always run) will execute in all environments, as they are not conditionally skipped.
-
Conditionally Skipping a Test:
(baseUrl === 'httpd://dev.yourdomain.com' ? it.skip() : it)('verify the notice is displayed')
, this will make the block ait.skip()
orit()
based on thebaseUrl
. This approach ensures that the test automatically adjusts based on the environment.
You can inject any condition like this to dynamically control your test :)
Why this approach?
Avoids Hardcoding Skips
Instead of manually commenting out tests for specific environments, Cypress handles it dynamically.Cleaner and More Maintainable
The logic for skipping tests is embedded within the test declaration, making it easy to follow and debug.Ensures Consistency Across Environments
You won't accidentally run tests in an environment where they shouldn't be executed.
Final Thoughts
Skipping tests dynamically based on environment settings is a smart way to ensure that your test suite remains clean, maintainable, and relevant across different environments. The method we discussed allows Cypress tests to self-adjust based on baseUrl, preventing unnecessary failures and keeping test execution focused where it matters.
See ya on another one.. Happy testing… ❤
Top comments (0)