Running specific tests in Cypress is important for effective debugging and quick feedback during development. Cypress allows you to isolate and run only the test cases or test files you’re focused on, Instead of executing the entire test suite, saving time and resources.
In this guide, learn how to run specific tests in Cypress along with the best practices.
Why do specific tests in Cypress?
Running specific tests in Cypress is important for speeding up development workflows, isolating issues, and increasing test efficiency. When working on large test suites, re-running the entire suite for every small code change can be time-consuming and unnecessary.
By targeting individual specs, developers can quickly validate functionality, debug failures, and iterate on test code without waiting for unrelated tests to complete. This helps to improve productivity and provides faster feedback during development and CI runs.
Key Benefits:
- Faster Iteration: Quickly test only the relevant parts of your application.
- Easy Debugging: Debug failed tests for easier troubleshooting.
- Targeted Validation: Run tests related to recent changes or specific features.
- Time Efficiency: Avoid running the entire suite when unnecessary.
Read More: Top 20 AI Testing and Debugging Tools
Command to Run Specific Test File in Cypress
To run a specific test file in Cypress, use the –spec flag with the npx cypress run command.
This tells Cypress to execute only the specified test file, rather than running the entire test suite. Here’s the basic syntax:
npx cypress run --spec "cypress/e2e/<file-name>.cy.js"
Example:
npx cypress run --spec "cypress/e2e/login.cy.js"
This command runs only the login.cy.js test file. A user can also provide a relative or absolute path to the spec file.
For targeting multiple files, use global patterns like:
npx cypress run --spec "cypress/e2e/auth/*.cy.js"
Beginning with Cypress
Let’s explore how to use Cypress to test a web application now that we are relatable with what it is and its advantages. Before beginning, make sure you clone the GitHub source.
Adding Cypress to our project is step one. The very first move you must do is access the project folder you just cloned in the terminal and run the following command to install all of its dependencies:
npm install
After the command has finished running, we’ll want to add Cypress to it by using the command that goes like this:
npm install cypress --save-dev
Go to the project’s root and find the package.json file. Inside the “script,” add the following:
"cypress:open": "cypress open", "cypress:run": "cypress run"
The final step is to launch Cypress directly from the npm command:
npm run test
A local instance of the website should be opened by your browser, along with a Cypress window, which you may now close. The local server might be terminated as well.
If a server is already running, Cypress just has to be started using npx Cypress open. However, you may use npm run test to start the default server.
- cypress run specific test:
cypress run --spec 'path/to/files/*.spec.js'
- cypress run specific test:
cypress run --spec path/to/file.spec.js
Learn how you can Run Cypress Tests with this Cypress Automation Tutorial
Launch your first BrowserStack Cypress test using Command Line
Get the BrowserStack CLI installed. A command-line program called the BrowserStack – Cypress CLI is used to facilitate communication between Cypress and BrowserStack. Install the BrowserStack – Cypress CLI as follows using the npm command:
# Install the BrowserStack Cypress CLI npm install -g browserstack-cypress-cli
Check out the Official Documentation to learn how to how to run your first test on BrowserStack
Creating a test in Cypress
Let’s write our first test now that Cypress has been introduced to our project. Navigate to /cypress/integration and add a mycart_spec.js file to it.
We’ll insert the following code into this file:
describe("Test Ecommerce features", () => { it("Test Ecommerce features", () => { cy.viewport(1366, 900); cy.visit("localhost:3000"); waitForSnipcartReady(); cy.get("#la-gioconda").click(); cy.get(".total").should("contain", "79.99", { timeout: 30000 }); expect(cy.get(".mycart-modal").should("exist")); });
With this, a 1366×900 viewport will be used to access our local page. Then, by catching the mycart.ready event, we establish a promise to wait for the mycart script to finish loading.
Under the global cy object you can see above, all of Cypress’s functionalities are accessible. No async/await is required. With the exception of the mycart event, which must be awaited since we need to capture the running document for this, tests run one step at a time, waiting for the completion of the preceding one.
Let’s run our initial test now that it has been created.
npm run test
The test we built ought to be visible in the Cypress window. Simply click it to get it running. This will launch a fresh window of the browser and launch the test automatically.
Run Cypress Tests on Real Devices
Testing a Single-Page Application
We’ll test a single-page application (SPA) in this demonstration that makes use of the React frontend framework. Users may add, edit, and remove tasks using the application’s simple task manager.
Installing certain dependencies is the first step. The following are necessary:
- React
- Create React App
- Cypress
With npm, we can set up these dependencies:
npm install --save react react-dom create-react-app cypress
We can now use Create React App: to create a new React app.
create-react-app my-app
The following additional Cypress dependencies must be installed next:
cd my-app npm install --save-dev cypress
We can now write our tests after installing our dependencies. In the cypress/integration folder, create a new file named tasks.spec.js and fill it with the following contents:
describe('Tasks', function() { beforeEach(function() { cy.visit('http://localhost:3000'); }); it('should add a task', function() { // Enter task details into form and submit cy.get('input[name="taskName"]').type('My Task'); cy.get('textarea[name="taskDescription"]').type('My Description'); cy.get('form').submit(); expect(cy.get('.tasks li').its('length')).to.equal(1); }); });
Before each test in the specification, the beforeEach function executes. In this instance, we are navigating to the main application URL, which is http://localhost:3000.
The ‘it’ function holds the location of our actual test code. A callback function containing our test code is the second argument, and the first argument is a description of the test scenario. This test verifies that when tasks are submitted via the form, our task management application appropriately adds them to the list. To do this, we first enter some information into the form fields, and then we submit it. There’s now one task in the list using expect.
Using npm, you may execute tests from a terminal window.
npm run e2e npm run e2e:open
Reliable results need running all Cypress tests on actual browsers. With BrowserStack, you can start testing the 30+ most recent browser versions on Windows and Mac. To achieve quicker results without compromising quality, use instant, hassle-free parallelization. By using BrowserStack to test the software under actual user situations, bugs can be found before users do.
How to Specify Specific Test Files using Cypress CLI?
Running specific test files using Cypress CLI is an efficient way to target only the relevant tests, especially when debugging or working on a focused feature. Cypress provides the –spec flag to control which test files are executed.
Step 1: Open your terminal and check for the project root directory.
Step 2: Use the –spec flag with npx cypress run to point to the exact test file for running:
npx cypress run --spec "cypress/e2e/login.cy.js"
Step 3: Use glob patterns for running multiple files that match a certain structure:
npx cypress run --spec "cypress/e2e/auth/*.cy.js"
Step 4: Target multiple specific files by separating them with commas:
npx cypress run --spec "cypress/e2e/login.cy.js,cypress/e2e/register.cy.js"
Step 5: Combine with other options like specifying browser or headed mode:
npx cypress run --spec "cypress/e2e/login.cy.js" --headed --browser chrome
Read More: What is Cypress Test Suite?
How to execute Cypress Tests with Cypress Test Runner?
The Cypress Test Runner helps to run, debug, and inspect your tests interactively in a real browser. It’s especially useful during development for live reloading, visual debugging, and inspecting test output in real time.
Steps to Run Tests Using the Cypress Test Runner
Here are the steps to be followed for running tests using the Cypress Test Runner:
Step 1: In your terminal, run:
npx cypress open
This launches the Cypress Test Runner UI.
Step 2: In Cypress 10+, select a testing type from:
Here, you can select E2E Testing and continue.
Step 3: Select the browser to run the tests (e.g. Chrome, Firefox, Edge).
Step 4: Pick the test file from the list shown in the UI. Click on any .cy.js or .cy.ts file to run it.
Step 5: The test will open in an actual browser window where you can:
- Inspect each command and assertion
- View the application state at each step
- Re-run or debug failed tests interactively
Step 6: Any changes made to the test code will automatically reload the test in the runner.
this.skip() for Running Specific Tests in Cypress
In Cypress, this.skip() is an efficient way to skip tests within a before, beforeEach, or any test hook.
It allows you to dynamically decide whether a test or a group of tests should run based on runtime conditions, such as environment variables, feature flags, or API responses. This is useful when certain tests are only relevant in specific environments or when a test case should be temporarily bypassed without commenting it out.
Example:
describe('Admin Panel Tests', function () { before(function () { if (Cypress.env('userRole') !== 'admin') { this.skip(); } }); it('should display the admin dashboard', () => { cy.visit('/admin'); cy.contains('Welcome, Admin').should('be.visible'); }); });
Use Case: Conditionally Skip a Single Test
In this use case, the test runs only in the staging environment and is skipped in all others using a runtime condition.
it('should only run in staging', function () { if (Cypress.env('ENV') !== 'staging') { this.skip(); } cy.visit('/beta-feature'); cy.contains('Staging Feature').should('exist'); });
Read More: How to install Cypress for Windows
Visual Studio Code Extension for Running Specific Tests in Cypress
To increase the productivity of Cypress testing workflows, Visual Studio Code (VS Code) provides several extensions that allow running specific tests or test files directly from the editor, without switching to the terminal. One of the most popular and effective extensions for this purpose is Cypress Snippets in combination with Cypress Test Runner or Cypress Helper.
These extensions provide features like inline test running, code lens actions above test blocks, and simple navigation to test files.
Popular VS Code Extensions for Cypress
Here are some of the popular VS Code extensions used for Cypress:
1. Cypress Test Runner for Visual Studio Code
- Add “Run” and “Debug” links above each describe() and it() block.
- Right-click any test and choose “Run Test” or “Debug Test”.
- Automatically run the test in the configured Cypress environment.
Example:
describe('Login Page', () => { it('should log in successfully', () => { cy.visit('/login'); cy.get('input[name="username"]').type('user'); cy.get('input[name="password"]').type('pass'); cy.get('.login-button').click(); cy.url().should('include', '/dashboard'); }); });
2. Cypress Snippets
They provide useful auto-completions and easy-to-modify test templates. While they don’t run tests directly, they speeds up test writing.
3. Code Runner
If configured correctly, with a code runner, a user can map custom Cypress run scripts to VS Code tasks.
Read More: How to set up Selenium on Visual Studio
Best Practices to run Specific Tests in Cypress
Cypress is a fantastic end-to-end testing tool that also has top-notch Best Practices documentation. Here is a second piece I’ve written that goes into more detail on Best practices.
In essence:
- Don’t utilise the UI to build up state; instead, set the state programmatically.
- Write specifications separately and prevent coupling.
- Try not to restrict yourself by acting like a user.
- Always be able to run tests independently and have them pass.
- Test just what you can control.
- To give your Cypress CSS Selectors context, use data-* attributes.
- Clean up state before tests run (not after).
Pro-Tip: Integrate your Test Suite with BrowserStack Automate. On a variety of actual mobile and tablet devices, such as the iPhone, iPad, Samsung Galaxy, Google Pixel, Nexus, and others, test your native and hybrid apps. For your fragmented online and mobile audience, create incredible applications.
Why Choose BrowserStack for Cypress Testing
BrowserStack is a cloud-based testing platform that lets you run Cypress tests efficiently across multiple device-OS-browser combinations. Here are a few reasons why you should choose BrowserStack:
- Cross-browser testing: Cypress runs on limited browsers, mainly Chrome-based ones. BrowserStack helps you expand your Cypress tests to many other browsers, such as Safari, Edge, IE, and more.
- Cloud Infrastructure: This cloud-based platform does not require setting up or maintaining browsers or physical devices locally.
- Parallel Testing: With parallel testing, you can run multiple Cypress tests concurrently, speeding up test execution and eventually the release cycles.
- Real-device testing: BrowserStack offers you a vast real-device cloud, letting you run Cypress tests on 3500+ real device, browser, and OS combinations, thus allowing you to test under real user conditions.
- Integrations: BrowserStack offers seamless integrations with several CI/CD tools like Jenkins, Travis CI, Circle CI, Bamboo and more.
- Scalability: BrowserStack supports real-device and parallel testing on a cloud-based infrastructure, enabling you to run hundreds of Cypress tests across different environments.
Conclusion
Without the hassles; Cypress can be set up in a matter of minutes. Cypress’s large user community is always eager to offer its expertise and insights. The syntax used in Cypress tests is pretty easy and simple to understand and write. You will be able to write effective UI tests with a little practice. For those who wish to develop pertinent end-to-end tests fast and efficiently, Cypress is a great option. It also makes problem-solving very simple.
Useful Resources for Cypress
Understanding Cypress
- Cross Browser Testing with Cypress : Tutorial
- Run Cypress tests in parallel without Dashboard: Tutorial
- Handling Test Failures in Cypress A Comprehensive Guide
- Cypress Test Runner: Tutorial
- Handling Touch and Mouse events using Cypress
- Cypress Automation Tutorial
- CSS Selectors in Cypress
- Performance Testing with Cypress: A detailed Guide
- Cypress Best Practices for Test Automation
- Test React Native Apps with Cypress
- Cypress E2E Angular Testing: Advanced Tutorial
- Cypress Locators : How to find HTML elements
- Maximizing Web Security with Cypress: A Step-by-Step Guide
- Conditional Testing in Cypress: Tutorial
- Cypress Web Testing Framework: Getting Started
- Cypress Disable Test: How to use Skip and Only in Cypress
- What’s new in Cypress 10? How it will change your current testing requirements
Use Cases
- How to Record Cypress Tests? (Detailed Guide)
- How to run your first Visual Test with Cypress
- How to Fill and Submit Forms in Cypress
- How to Automate Localization Testing using Cypress
- How to run Cypress Tests in Chrome and Edge
- How to use Cypress App Actions?
- How to Run Cypress Tests for your Create-React-App Application
- How to Run Cypress Tests in Parallel
- How to handle Click Events in Cypress
- How to Test React using Cypress
- How to Perform Visual Testing for Components in Cypress
- How to run UI tests in Cypress
- How to test redirect with Cypress
- How to Perform Screenshot Testing in Cypress
- How to write Test Case in Cypress: (with testing example)
Tool Comparisons