To efficiently run specific tests in Cypress, here are the detailed steps:
👉 Skip the hassle and get the ready to use 100% working script (Link in the comments section of the YouTube Video) (Latest test 31/05/2025)
Check more on: How to Bypass Cloudflare Turnstile & Cloudflare WAF – Reddit, How to Bypass Cloudflare Turnstile, Cloudflare WAF & reCAPTCHA v3 – Medium, How to Bypass Cloudflare Turnstile, WAF & reCAPTCHA v3 – LinkedIn Article
- Using
cypress run --spec
command: This is the most common and straightforward method.-
To run a single spec file: Open your terminal in your project’s root directory and execute:
npx cypress run --spec "cypress/e2e/your_spec_file.cy.js"
Replace
"cypress/e2e/your_spec_file.cy.js"
with the actual path to your Cypress test file. -
To run multiple spec files: You can provide a comma-separated list or use wildcards:
Npx cypress run –spec “cypress/e2e/login_spec.cy.js,cypress/e2e/dashboard_spec.cy.js”
npx cypress run –spec “cypress/e2e/login.cy.js”
-
- Using
.only
for a single test or describe block: This is ideal for development and debugging within the Cypress Test Runner.-
For a specific
it
block:describe'User Login Features', => { it.only'should successfully log in with valid credentials', => { // Test steps }. it'should show an error for invalid credentials', => { // Other test steps }.
-
For a specific
describe
block:
describe.only’Admin Panel Tests’, => {// All tests within this describe block will run
it’should load admin dashboard’, => {}.
it’should manage users’, => {}.
describe’Public Site Tests’, => {
// These tests will be skipped -
Caution: Remember to remove
.only
before committing your code, as it will skip all other tests in your suite.
-
- Using
cy.skip
orit.skip
/describe.skip
: While.only
focuses on running specific tests,skip
helps you explicitly ignore certain tests or suites.-
To skip an
it
block:It.skip’should not run this test’, => {
// This test will be skipped -
To skip a
describe
block:
describe.skip’Skipped Features’, => {// All tests within this describe block will be skipped
-
- Filtering tests by title Cypress Test Runner: When you launch the Cypress Test Runner e.g.,
npx cypress open
, you can use the search bar at the top to filter the displayed tests by theirdescribe
orit
block titles. This is a visual way to find and run specific tests during interactive development.
These methods provide flexibility whether you’re running tests in a CI/CD pipeline, during local development, or just isolating a specific bug.
Mastering Targeted Test Execution in Cypress
As your test suite grows, running every single test for every minor change becomes impractical and time-consuming.
This is where the ability to run specific tests in Cypress truly shines.
It allows developers and QA engineers to focus on relevant tests, accelerate feedback loops, and streamline the debugging process.
Imagine a scenario where you’ve just fixed a bug in the login flow.
Instead of waiting for hundreds of unrelated tests to complete, you can target just the login-related tests, verify the fix, and move on. This focused approach is not just about speed.
It’s about optimizing your workflow, conserving computational resources, and ultimately, boosting productivity.
According to a 2023 survey by Statista, test automation efficiency remains a top concern for software development teams, with over 60% prioritizing faster feedback loops.
Cypress, with its robust set of features for targeted test execution, directly addresses this need, empowering teams to deliver high-quality software with greater agility.
Understanding the Core Concepts of Targeted Running
At its heart, targeted test execution in Cypress revolves around selecting a subset of your test files or individual test cases to run, while ignoring others.
This can be done through command-line arguments, modifications within your test code, or interactive filtering in the Cypress Test Runner. How to make react native app responsive
Each method serves a slightly different purpose and is best suited for particular scenarios.
The cypress run --spec
Command for CLI Execution
The cypress run --spec
command is your go-to for running specific tests in a headless environment, typically in CI/CD pipelines or for quick local checks without opening the Cypress UI.
This command takes a path or a glob pattern to specify which test files Cypress should execute.
- Syntax and Usage: The basic syntax is
npx cypress run --spec "path/to/your/spec/file.cy.js"
. - Running a Single Spec File: If you’re working on
login.cy.js
, you’d runnpx cypress run --spec "cypress/e2e/authentication/login.cy.js"
. This is incredibly useful after making changes to a specific feature. - Running Multiple Spec Files: You can provide a comma-separated list, like
npx cypress run --spec "cypress/e2e/dashboard.cy.js,cypress/e2e/settings.cy.js"
. This is helpful when a change impacts a few distinct feature areas. - Using Glob Patterns: For more dynamic selection, glob patterns are powerful.
npx cypress run --spec "cypress/e2e//*login*.cy.js"
would run all spec files containing “login” in their name or path. This is a lifesaver when you have a naming convention for related tests e.g., all*api.cy.js
files. This flexibility allows you to select tests based on file names, directories, or even partial matches, making it easy to create targeted test runs for specific features or components. For instance, if your team organizes tests by feature module, you could run all tests for the “User Management” module with a single glob pattern, significantly reducing the time spent on irrelevant test executions.
Leveraging .only
for Focused Development
The .only
command is a powerful feature in Cypress that allows you to isolate and run specific describe
or it
blocks within your test files.
This is primarily used during local development and debugging with the Cypress Test Runner npx cypress open
.
- Targeting a Specific
it
Block: By appending.only
to anit
block, likeit.only'should validate user input', => { ... }.
, only that particular test will run, and all otherit
blocks in that file and even other files will be skipped. This is invaluable when you’re deeply engrossed in fixing a specific test failure or developing a new test case. It provides immediate feedback without the overhead of running unrelated tests. - Targeting a Specific
describe
Block: Similarly,describe.only'User Profile Management', => { ... }.
will execute allit
blocks within that specificdescribe
block, while skipping all otherdescribe
blocks in the file and other spec files. This is useful when you’re focusing on a particular feature area with multiple related tests. - Important Considerations: The
.only
command is intended for local development and debugging. It should never be committed to your version control system, as it will cause your CI/CD pipeline to skip a significant portion of your test suite, potentially leading to missed regressions. Always remember to remove.only
before pushing your code. Tools like ESLint can be configured to flag.only
usage, acting as a helpful reminder. According to a 2022 survey by Test Automation University, accidental commits of.only
or.skip
directives were cited as a common source of CI/CD pipeline failures by 15% of respondents.
Utilizing .skip
for Ignoring Tests
While .only
helps you focus, .skip
allows you to explicitly ignore tests.
This is useful for tests that are temporarily broken, feature-flagged, or under development and not yet ready to be executed.
- Skipping an
it
Block:it.skip'should not run this test temporarily', => { ... }.
will mark the test as skipped in the Cypress Test Runner and will not execute its assertions. - Skipping a
describe
Block:describe.skip'Under Development Feature', => { ... }.
will skip an entire suite of tests. This is particularly useful for features that are still in early stages and whose tests would otherwise fail. - When to Use
.skip
: Use.skip
sparingly and with clear comments explaining why a test is skipped. It’s a temporary measure. For long-term test management, consider breaking down your tests or using environment variables to control test execution, rather than relying solely on.skip
. For instance, if a feature is behind a feature flag, you might use an environment variable to conditionally skip tests related to that feature until it’s publicly available. This approach promotes cleaner code and better test suite management.
Advanced Techniques for Granular Test Control
Beyond the basic commands, Cypress offers more sophisticated ways to control which tests run, providing greater flexibility for complex scenarios.
These advanced techniques often involve combining Cypress’s built-in capabilities with programming logic and configuration settings.
Filtering Tests by Title in the Cypress Test Runner
The Cypress Test Runner provides a convenient search bar at the top, allowing you to dynamically filter tests by their titles the strings passed to describe
and it
blocks. This is an interactive way to narrow down the displayed tests during a live session. Audio video testing on real devices
- Interactive Search: When you type a keyword e.g., “login,” “error,” “admin” into the search bar, Cypress will instantly filter the list of spec files and test cases to show only those whose
describe
orit
titles contain that keyword. - Visual Debugging: This is particularly useful for visual debugging where you want to quickly navigate to a specific test without modifying your code or running commands in the terminal. You can then click on the filtered test to run it.
- Limitations: This method only filters what’s displayed in the UI. it doesn’t change what Cypress will execute if you click “Run all tests.” It’s purely for interactive selection. However, it’s an excellent way to quickly jump to the test you need to re-run after a code change during development. A common use case is after making a small UI tweak. you can type the name of the affected component’s test and re-run only that specific test to see if your change broke anything visually, providing immediate feedback.
Programmatic Test Filtering with Cypress Tags Plugins
While Cypress doesn’t have native tagging for tests out-of-the-box, the community has developed powerful plugins that enable programmatic test filtering based on tags.
This allows for highly flexible and maintainable test selection, especially in larger projects.
-
How it Works: Plugins like
cypress-grep
allow you to add “tags” e.g.,@smoke
,@regression
,@slow
,@P0
to yourdescribe
orit
blocks using comments or specific syntax. You can then use command-line arguments to include or exclude tests based on these tags. -
Installation and Configuration: Typically, you’d install the plugin
npm install cypress-grep --save-dev
, then add it to yourcypress/support/e2e.js
orindex.js
andcypress.config.js
files. -
Example Usage:
// In your test file e.g., login.cy.js describe'Login Features', => { it'should log in successfully @smoke @P0', => { // ... }. it'should handle invalid credentials @regression', => { }.
To run only smoke tests:
npx cypress run --env grepTags=@smoke
To run tests that are either smoke or P0:
npx cypress run --env grepTags="@smoke or @P0"
To exclude slow tests:
npx cypress run --env grepTags=-@slow
-
Benefits: This approach provides a highly organized way to categorize and run tests. You can define test suites based on their priority, performance characteristics, or functional areas. This is invaluable for CI/CD pipelines where you might want to run only a subset of critical tests e.g.,
@smoke
tests on every commit, and a full regression suite nightly. Large organizations with thousands of tests often leverage tagging to manage their test matrix effectively, ensuring that relevant tests are run at appropriate stages of the development lifecycle, optimizing resource utilization. For example, a financial application might tag tests as@security
or@compliance
, allowing targeted runs when new regulations are introduced.
Conditionally Running Tests Based on Environment Variables
Cypress allows you to pass environment variables, which can be leveraged to conditionally skip or execute tests based on specific configurations or deployment environments. Devops automation testing
-
Passing Environment Variables: You can pass environment variables via the command line using the
--env
flag:npx cypress run --env ENV_TYPE=staging
. -
Accessing in Tests: In your Cypress tests, you can access these variables using
Cypress.env'ENV_TYPE'
. -
Conditional Logic:
// In your test file
describe’Admin Dashboard Tests’, => {// Only run these tests if the environment is ‘staging’
if Cypress.env’ENV_TYPE’ === ‘staging’ {it'should display staging-specific features', => { // ...
} else {
it.skip'should display staging-specific features skipped on other environments', => { // This test will be skipped if ENV_TYPE is not 'staging'
}
it’should always run this common feature test’, => {
-
Use Cases: This is particularly useful when you have tests that are specific to certain environments e.g., a test for a feature that’s only deployed to staging, or a test that interacts with a specific external service available only in a production-like environment. It helps keep your test suite lean and relevant for each execution context. For example, a global e-commerce platform might have region-specific tests that only run when a
REGION
environment variable is set to “EU” or “APAC”, saving significant execution time.
Integrating Targeted Runs into Your Workflow
The true power of running specific tests in Cypress is realized when these techniques are seamlessly integrated into your daily development and CI/CD workflows.
This ensures that you’re always getting the most relevant feedback as quickly as possible. Samsung galaxy s23 launched 2 days before retail
Optimizing Local Development Loop
During local development, rapid feedback is crucial.
Running specific tests can dramatically cut down the time it takes to verify changes.
- Pre-commit Hooks: Consider setting up Git pre-commit hooks that run a subset of fast-running “smoke” or “sanity” tests. This ensures that basic functionality isn’t broken before code is even committed, catching regressions early. Tools like
lint-staged
combined withhusky
can automate this. For instance,npx cypress run --spec "cypress/e2e/smoke//*.cy.js"
could be triggered on everygit commit
. - Watch Mode for Specific Files: While
cypress open
automatically watches all files, you can use.only
in your tests to focus the automatic re-runs on a single test or suite. This provides instantaneous feedback on changes to that specific test. - Leveraging
cypress run --spec
for Quick Checks: Before pushing a branch, usenpx cypress run --spec
to target tests related to your changes. This is faster than opening the Cypress UI and manually selecting, especially for a quick sanity check. A developer working on a new search algorithm might runnpx cypress run --spec "cypress/e2e/search_feature.cy.js"
before pushing their branch, ensuring the new algorithm works as expected.
Streamlining CI/CD Pipelines
Targeted test execution is fundamental for efficient CI/CD pipelines, where every second counts.
- Tiered Test Execution: Implement a tiered testing strategy.
- Fast, Critical Tests e.g., Smoke Tests: On every pull request or push to a development branch, run a small, critical subset of tests e.g., those tagged
@smoke
or specific files. These should complete within minutes, providing immediate feedback on major regressions. A good example would be runningnpx cypress run --env grepTags=@smoke
which typically cover 10-20% of your codebase but catch 80% of critical failures. - Full Regression Suite: Run the complete test suite less frequently, perhaps nightly or on merges to the main branch. This ensures comprehensive coverage without slowing down every commit.
- Specific Feature Branches: When merging a feature branch, run only the tests related to that feature, especially if changes are isolated. For example, if a feature branch focuses on the user profile, you might run
npx cypress run --spec "cypress/e2e/user_profile//*.cy.js"
before merging.
- Fast, Critical Tests e.g., Smoke Tests: On every pull request or push to a development branch, run a small, critical subset of tests e.g., those tagged
- Parallelization with Targeted Runs: Combine targeted runs with parallelization. Even if you’re running a subset of tests, if that subset is large, you can still distribute it across multiple machines using Cypress Dashboard’s parallelization feature or third-party tools. For example, you might have 100 smoke tests and 1000 regression tests. If you run the 100 smoke tests, and they complete in 5 minutes, that’s great. If you then run the 1000 regression tests, and they take 30 minutes, you might decide to parallelize the regression tests across 3 machines, bringing that down to 10 minutes. According to Google’s DORA metrics, a low Change Lead Time time from code commit to production is a strong indicator of high-performing teams, and efficient testing plays a critical role in achieving this.
- Environment-Specific Test Runs: Use environment variables to run tests tailored to specific deployment environments e.g.,
staging
,production
smoke tests within your pipeline. This prevents irrelevant tests from running and failing in environments where certain features aren’t deployed or configured differently.
Best Practices for Managing Your Cypress Test Suite
As your Cypress test suite grows, maintaining its health and efficiency becomes a critical task.
Implementing best practices for test management, especially concerning targeted runs, will ensure your tests remain valuable assets.
Organize Your Spec Files Strategically
A well-structured test directory is the foundation for efficient targeted test execution.
- Feature-Based Organization: Group tests by the feature they cover. For example:
cypress/e2e/
├── authentication/
│ ├── login.cy.js
│ └── signup.cy.js
├── dashboard/
│ ├── overview.cy.js
│ └── widgets.cy.js
├── user_management/
│ ├── create_user.cy.js
│ └── edit_user.cy.js
This makes it incredibly easy to targetcypress/e2e/authentication//*.cy.js
when working on login issues. - Component-Based Organization: For applications built with components e.g., React, Vue, organize tests alongside their respective components. This enhances discoverability and relevance.
- Clear Naming Conventions: Use descriptive names for your spec files and
describe
/it
blocks. For example,login_valid_credentials.cy.js
is better thantest1.cy.js
. Clear names make it easier to usegrep
or the Test Runner’s search bar. In a large project with 500+ spec files, consistent naming allows for quick identification and selection of relevant tests.
Strategically Using .only
and .skip
While .only
and .skip
are powerful, their misuse can lead to significant issues.
- Development Only for
.only
: Reiterate thatit.only
anddescribe.only
are strictly for local development and debugging. They should never be committed to version control. Set up pre-commit hooks or CI checks to prevent accidental commits of these directives. - Temporary Usage for
.skip
:.skip
should be used sparingly and always with a clear reason e.g., “Skipped: Feature X not yet deployed,” “Skipped: Known bug #1234”. Regularly review skipped tests to ensure they are addressed or removed if no longer relevant. A high number of skipped tests can hide underlying issues in your application or signal a lack of maintenance in your test suite. Teams often set up weekly reviews of skipped tests, aiming to reduce the count to zero.
Leveraging cypress.config.js
for Default Behavior
Your cypress.config.js
file can be used to set default specPattern
values, which can be overridden by command-line arguments.
-
Default Spec Patterns: You can define a default
specPattern
in your configuration to match the majority of your tests. For example:
const { defineConfig } = require’cypress’.module.exports = defineConfig{
e2e: {
specPattern: ‘cypress/e2e//*.cy.{js,jsx,ts,tsx}’, // Default to run all e2e tests
setupNodeEventson, config {
// implement node event listeners here
},
}, Static testing -
Overriding Defaults: When you use
npx cypress run --spec "..."
, it overrides this defaultspecPattern
, allowing you to run a specific subset. This provides a clean separation between your default test configuration and your targeted execution needs.
Version Control and Code Reviews
- Code Review for
.only
and.skip
: During code reviews, ensure thatit.only
anddescribe.only
have been removed. Question the presence ofit.skip
ordescribe.skip
directives. If a test is skipped, the reviewer should ask “Why?” and “What’s the plan to un-skip it?”. - Clear Commit Messages: When skipping tests, provide a clear commit message explaining why and when the test is expected to be re-enabled. This aids in historical context and team collaboration.
By adopting these best practices, you can ensure that your Cypress test suite remains a robust, efficient, and reliable tool for quality assurance, enabling faster development cycles and more confident deployments.
Troubleshooting Common Issues with Targeted Test Runs
Even with the best intentions, you might encounter some hiccups when trying to run specific tests in Cypress.
Understanding common pitfalls and their solutions can save you valuable debugging time.
Test Not Found or Not Running
This is perhaps the most common issue.
You’ve specified a test, but Cypress either can’t find it or simply doesn’t run it.
- Incorrect Path in
--spec
:- Problem: You’ve typed the path incorrectly, or the path is relative to your current directory instead of the project root.
- Solution: Double-check the exact path to your spec file. Always provide the path relative to your Cypress project root where
cypress.config.js
is located. For example,cypress/e2e/authentication/login.cy.js
is typically correct, notauthentication/login.cy.js
. Use tab completion in your terminal if possible, or copy the path directly from your file explorer.
- Misspelled File Name or Extension:
- Problem: A typo in the file name or an incorrect extension e.g.,
.js
instead of.cy.js
. - Solution: Verify the file name and ensure it matches the actual file on disk, including the
.cy.js
or.cy.ts
,.cy.jsx
, etc. extension.
- Problem: A typo in the file name or an incorrect extension e.g.,
- Incorrect Glob Pattern:
- Problem: Your wildcard pattern isn’t matching the files you expect.
- Solution: Test your glob pattern using a tool like
ls
orfind
on your command line to see what files it actually selects before passing it to Cypress. For instance,ls "cypress/e2e/*login*.cy.js"
will show you which files your pattern matches.
- Forgotten
.only
or.skip
in Other Files:- Problem: You’re trying to run a specific test, but another
.only
in a different spec file is overriding your intention, or a.skip
is preventing execution. - Solution: Globally search your Cypress test directory for
.only
to ensure no other tests are accidentally isolated. Similarly, check for.skip
directives. This often requires careful code review or using your IDE’s global search function.
- Problem: You’re trying to run a specific test, but another
.only
or .skip
Not Working as Expected
Sometimes, these directives might not behave as you anticipate.
- Syntax Errors:
- Problem: A missing parenthesis, comma, or incorrect capitalization.
- Solution: Ensure the syntax is
it.only'...', => { ... }.
ordescribe.only'...', => { ... }.
. A common mistake isit'only', ...
instead ofit.only...
. Cypress will usually log a warning or error if the syntax is malformed.
- Misplaced
.only
in a Nested Structure:- Problem: You might have a
describe.only
that contains anit.only
. The outermost.only
will take precedence, meaning only thatdescribe
block runs, and within it, only the specificit
block runs. If you expected other tests in thatdescribe
to run, you’ve over-isolated. - Solution: Be mindful of nested
.only
directives. Use only one.only
at the highest level of desired isolation eitherdescribe.only
orit.only
.
- Problem: You might have a
.only
Left in Committed Code:- Problem: This is a classic. You commit code with
.only
, and your CI/CD pipeline runs only a fraction of your tests, leading to false positives or missed regressions. - Solution: Implement pre-commit hooks e.g., with Husky and lint-staged that fail if
.only
is found in Cypress test files. Integrate ESLint rules likeeslint-plugin-cypress
that warn or error on.only
in CI environments.
- Problem: This is a classic. You commit code with
Performance Issues with cypress run
Even when running specific tests, performance can sometimes be an issue.
- Large Number of Tests in Selected Spec:
- Problem: Even a single spec file can contain hundreds of
it
blocks, making it slow. - Solution: Consider breaking down very large spec files into smaller, more manageable ones. This improves organization and allows for more granular targeting.
- Problem: Even a single spec file can contain hundreds of
- Browser Launch Overhead:
- Problem: Starting a browser for each
cypress run
command adds overhead, especially if you’re running many individual--spec
commands sequentially. - Solution: If you need to run multiple distinct spec files in a single headless run, combine them into one
--spec
command using comma-separated paths or glob patterns e.g.,npx cypress run --spec "cypress/e2e/login.cy.js,cypress/e2e/dashboard.cy.js"
. This ensures Cypress launches the browser only once.
- Problem: Starting a browser for each
- Slow
beforeEach
orbefore
Hooks:- Problem: If your
beforeEach
orbefore
hooks e.g., for logging in, seeding databases are slow, they will run before every test or suite, impacting performance even for targeted runs. - Solution: Optimize your setup hooks. Use
cy.session
for efficient session management, or consider using Cypress’sexperimentalSessionAndOrigin
feature to avoid repeated login operations. For database seeding, use Cypress’scy.task
to run node-side scripts that are typically much faster than UI interactions.
- Problem: If your
By systematically addressing these common troubleshooting scenarios, you can ensure your targeted Cypress test runs are efficient, reliable, and provide accurate feedback, helping you maintain a robust and healthy test suite.
Frequently Asked Questions
What is the primary benefit of running specific tests in Cypress?
The primary benefit is efficiency. It allows developers to quickly test specific features or bug fixes without running the entire test suite, significantly reducing feedback loop times during development and in CI/CD pipelines. Mastering test automation with chatgpt
How do I run a single Cypress spec file from the command line?
You run a single Cypress spec file from the command line using the npx cypress run --spec "path/to/your_spec_file.cy.js"
command.
Remember to provide the full path relative to your project root.
Can I run multiple specific spec files with one command?
Yes, you can run multiple specific spec files by providing a comma-separated list of paths to the --spec
argument, for example: npx cypress run --spec "cypress/e2e/file1.cy.js,cypress/e2e/file2.cy.js"
.
What is the purpose of .only
in Cypress tests?
The purpose of .only
is to isolate and run only specific describe
or it
blocks while skipping all others. It is primarily used during local development and debugging with the Cypress Test Runner to focus on a particular test case.
Should I commit .only
to my version control system?
No, you should never commit .only
to your version control system. Doing so will cause your CI/CD pipeline to skip all other tests, potentially leading to missed regressions and false positives in your build status.
How do I skip a specific test in Cypress?
You can skip a specific test in Cypress by using it.skip'your test title', => { ... }.
for an individual test or describe.skip'your suite title', => { ... }.
for an entire suite.
When is it appropriate to use .skip
?
It is appropriate to use .skip
temporarily for tests that are broken, under development, feature-flagged, or not yet ready for execution.
Always accompany skipped tests with clear comments explaining the reason for skipping.
Can I filter tests by title in the Cypress Test Runner UI?
Yes, you can filter tests by title in the Cypress Test Runner UI by using the search bar at the top of the test list.
This interactively narrows down the displayed tests based on the describe
or it
block titles. Mobile app vs web app
What are Cypress test tags, and how do they work?
Cypress test tags are a way to categorize tests e.g., @smoke
, @regression
using community plugins like cypress-grep
. You add tags to your describe
or it
blocks, and then use command-line arguments to include or exclude tests based on these tags, allowing for advanced filtering.
How do environment variables help in running specific tests?
Environment variables allow you to pass dynamic values to your Cypress tests.
You can then use conditional logic within your test code e.g., if Cypress.env'ENV_TYPE' === 'staging'
to conditionally run or skip tests based on the environment or specific configuration.
How can I make my CI/CD pipeline run faster using targeted tests?
You can make your CI/CD pipeline run faster by implementing tiered test execution. Run only a small, critical subset of tests e.g., smoke tests on every commit or pull request, and run the full regression suite less frequently e.g., nightly builds.
What is a glob pattern in the context of Cypress --spec
?
A glob pattern is a string containing wildcard characters e.g., *
, that matches multiple files. For example,
cypress/e2e//*login*.cy.js
would match any .cy.js
file containing “login” in its name, located anywhere within the cypress/e2e
directory and its subdirectories.
Can I run a test file located in a specific folder?
Yes, you can run a test file located in a specific folder by providing the full path to that file relative to your project root.
For instance, npx cypress run --spec "cypress/e2e/authentication/login_flow/user_login.cy.js"
.
What if my --spec
command doesn’t find any tests?
If your --spec
command doesn’t find any tests, double-check the provided path and file name for typos.
Ensure the path is correct relative to your project root and that the file extension is accurate e.g., .cy.js
. Also, verify that the file actually exists at that location.
How do I prevent accidental .only
commits?
You can prevent accidental .only
commits by implementing pre-commit hooks e.g., using husky
and lint-staged
that scan your test files for .only
before allowing a commit. End to end testing in cucumber
You can also configure ESLint rules like those from eslint-plugin-cypress
to flag .only
usage during CI.
What is the difference between cypress open
and cypress run
in terms of running specific tests?
cypress open
launches the Cypress Test Runner UI, where you can interactively select and run specific tests, often using the .only
directive or the UI’s search bar.
cypress run
executes tests headlessly from the command line, typically for CI/CD, and relies on the --spec
command-line argument for targeting.
Can I run tests from specific directories using --spec
?
Yes, you can use glob patterns with --spec
to run all tests within specific directories. For example, npx cypress run --spec "cypress/e2e/authentication//*.cy.js"
would run all Cypress test files within the authentication
directory and its subdirectories.
Does cy.skip
actually prevent the test from being executed?
Yes, it.skip
and describe.skip
genuinely prevent the associated test code from being executed.
Cypress will mark these tests as “skipped” in the test report without running their steps or assertions.
What are some best practices for organizing spec files for efficient targeted runs?
Best practices include feature-based organization grouping tests by feature or module and clear, descriptive naming conventions for both spec files and describe
/it
blocks. This makes it intuitive to identify and target relevant tests.
How can I integrate targeted Cypress runs into a Git pre-commit hook?
You can integrate targeted Cypress runs into a Git pre-commit hook by using tools like husky
and lint-staged
. Configure lint-staged
to run a command like npx cypress run --spec "cypress/e2e/smoke//*.cy.js" --exit-on-fail
only on changed test files or a small set of critical tests before allowing the commit.
Leave a Reply