App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide How to run specific test in Cypress

How to run specific test in Cypress

By Hamid Akhtar, Community Contributor -

Modern JavaScript testing frameworks make it simple to deliver high-quality web apps, as no one wants to spend time troubleshooting one once it has been released. You’ve automated debugging with Selenium and other tools to make sure your app is operating as intended before going live, but increasingly intricate JavaScript code might cause them to malfunction.

Additionally, single-page apps replaced multi-page websites, primarily attributed to frameworks like React, Vue.js, or Angular (SPA). This requires creating more complex JavaScript code, potentially breaking tools like Selenium. Then Cypress, a cutting-edge, frontend-focused testing framework for modern web apps, stepped in.

Let’s dive into what Cypress is and how you may use it.

Why do specific tests in Cypress?

Unifying web app testing regardless of the programming language used is the goal of Cypress, a modern and comprehensive end-to-end testing framework. Every platform and browser arise compatible with it. Cypress furthermore provides a browser-based integrated development environment (IDE) that you open in your browser.

Unit and integration testing are both doable with Cypress. With the use of an event-based architecture that hooks into Google Chrome’s lifecycle events, it can wait for things like Ajax requests to finish without utilizing a polling or timeout mechanism. Consequently, testing becomes accurate and quick.

With features like time travel, current and previous state diff-ing, live code reloading, and more, Cypress.io may be compared to Redux for automated testing. 

The goal is to test applications using the same development stack. Cypress is different from other test-related tools. It is an open-source testing framework that incorporates a lot of amazing features, like headless browser testing, screenshots, video capturing, in-browser debugging, asynchronous testing, etc. To test your website across a range of browsers and devices, Cypress also offers a CLI.

The nice thing is that you will witness everything unfolding in front of you. When you save your changes in the test file, you may rapidly see your tests running on a second monitor. This will save you a ton of time when writing tests, fixing broken tests, and making tests interesting to write.

To put it briefly, it represents both the ideal state of Cypress End to End testing and its true future.

What sets Cypress and Selenium apart from each other?

While Selenium may be used to test a variety of apps, Cypress is mainly meant for testing web applications. Cypress offers a considerably more streamlined and user-friendly interface than Selenium. This makes it much simpler to comprehend and put into practice for novice testers. Cypress runs immediately in the browser, which speeds up the testing process. Selenium WebDriver, on the other hand, uses a driver that communicates with the browser via HTTP. Cypress creates tests in JavaScript and executes them in browsers. Although Selenium has its own scripting language called Selenese, you may also use JavaScipt, C#, Ruby, and Python.

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.

Run Cypress Tests on BrowserStack

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. 

Try BrowserStack for Free

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.

Tags
Automation Testing Cypress

Featured Articles

Cypress Best Practices for Test Automation

How to write Test Case in Cypress: (with testing example)

Curated for all your Testing Needs

Actionable Insights, Tips, & Tutorials delivered in your Inbox
By subscribing , you agree to our Privacy Policy.
thank you illustration

Thank you for Subscribing!

Expect a curated list of guides shortly.