While conditionally skipping entire tests is likely rare, there are use-cases in which this might be desired. One, primary example includes feature flagging; where a test should only run only when a certain flag or condition is enabled.
Cypress used to support a plugin called cypress-skip-test. The plugin provided a few commands to skip and run tests based on certain conditions the user would provide. While it’s several years archived at this point, the underlying functionality of these commands can be stripped to create a Custom command that still works just fine today.
Therefore I present to you, the onlyOn
custom command, simplified.
/** Action that conditionally skips tests based on a given input */
Cypress.Commands.add('onlyOn', (enabled: boolean) => {
if (enabled !== true) {
cy.state('runnable').ctx.skip()
}
})
That’s it, it’s very simple.
The command accepts a condition, which can be anything you define. If that condition isn’t true, then the current test state is automatically updated to skipped. Otherwise, it will continue to execute like normal. The condition can come from an env file, fetched from a 3rd party service (such as LaunchDarkly or Statsig), or any other customized implementation unique to you.
To use it, just copy that command and add it into your suite of custom commands (support/commands.js
by default).
Next, the command can be called from any of the normal Cypress hooks like in the example below.
describe("Skip all the tests", () => {
beforeEach(() => {
// Will skip all tests in the `describe` if false
cy.onlyOn(myFeatureFlag.someFeature)
cy.visit("/my site");
});
it("skip test", () => {
// Some test code
});
it("skip another test", () => {
// Some test code
});
});
describe("Skip one of the tests", () => {
beforeEach(() => {
cy.visit("/my site");
});
it("run test", () => {
// Some test code
});
it("skip test", () => {
// Will skip only this test if false
cy.onlyOn(myFeatureFlag.someFeature)
// Some test code
});
});
That’s it, easy enough. I encourage you to get creative with the conditions you pass in based on need.
While this is just one example, there are many other ways to skip tests, such as utilizing tagging and spec configurations. I suggest checking out these resources for expanded examples, especially for conditional validations within the tests themselves.
Skip test conditionally with Cypress
Conditional testing | Cypress examples (v13.13.1)
Happy testing!
Top comments (0)