Web Application Development

Cypress with Vue: Enhanced Automation Testing for Vue Projects

Blog bannerBlog banner

Introduction to Cypress with vue

Automation testing is a pivotal part of contemporary web development, ensuring applications function correctly and instilling confidence in our codebase. Cypress is a cutting-edge, JavaScript-based front-end testing tool tailored for the modern web. It provides robust support for web frameworks, enabling developers to write end-to-end, integration, and unit tests with ease. With its rich API, real-time reloads, and automatic waiting, Cypress is particularly well-suited for testing Vue.js applications.

Key Features of Cypress in Vue Projects

Time-Saving:

Enjoy rapid test execution speeds, which lead to quicker feedback cycles and expedited development iterations.

Time Travel Debugging:

Unique to Cypress, this feature captures snapshots as your tests run, allowing you to review each step for effective debugging.

Automatic Waiting:

No need for manual waits; Cypress waits for elements to load before executing commands.

Developer Experience:

Clear syntax, helpful error messages, and visual debugging tools simplify the process of writing and debugging tests.

Network Mocks:

Simulate API responses and control network behaviour for thorough testing.

Fast Feedback:

Detailed logs and screenshots for failed tests facilitate swift issue resolution.

Real-Time Reload:

Cypress automatically reloads your tests as you make changes to your application, providing immediate feedback.

All-in-One Solution:

Comprehensive support for end-to-end, integration, and component testing.

Visual Testing:

Capture screenshots and record videos of test runs to identify visual regressions.

Real-Time UI:

A real-time UI displays tests running, helping you understand the process during execution.

Real Browser Testing:

Cypress runs tests in real browsers (Chrome, Firefox, Edge) for realistic testing.

Spies, Stubs, and Clocks:

Verify and control function behaviors, server responses, or timers.

Setting Up Cypress in a Vue 3 Project

Installation:

Code

    npm install cypress --save-dev
    # or
    yarn add cypress --dev
            

Initialization:

Code

    npx cypress open
            

This creates a `cypress` folder in your project directory with example tests and configurations.

Script Addition:

Code

    {
        "scripts": {
            "cy:open": "cypress open",
            "cy:run": "cypress run --component"
        }
    }
            

Commands:

Code

    npm run cy:open  # Opens Cypress in the selected browser
    npm run cy:run   # Runs component tests in the terminal
            

Alternative Setup:

For a fresh Vue 3 project with Cypress:

Code

    npm init vue@latest
            
Cypress with Vue

Choose E2E Testing, and a configuration file will be added to your project directory.

End-to-End Testing with Cypress

End-to-end (E2E) testing involves testing the entire application workflow, from start to finish, simulating user interactions. Here’s how to add your first test:

Create a Test File:

Code

    # Add a new spec file in cypress/e2e/spec.cy.js
            

Once we've created that file, you should see it immediately displayed in the list of end-to-end specs. Cypress monitors your files for any changes and automatically displays any changes.

Cypress with Vue

Example Test:

Code

    describe('Todo tests', () => {
        it('should display empty state message', () => {
            cy.visit('/');
            cy.get('.empty-state-message').contains('No Data Available.').should('be.visible');
        });
        
        it('should add todo', () => {
            cy.visit('/');
            cy.get('input[type="text"]').type('new todo{enter}');
            cy.get('ul').contains('new todo').should('be.visible');
            cy.get('ul').find('li').should('have.length', 1);
        });
        
        it('should delete todo', () => {
            cy.visit('/');
            cy.get('input[type="text"]').type('new todo{enter}');
            cy.get('ul').find('li').first().find('button').click();
            cy.get('ul').find('li').should('have.length', 1);
        });
    });
            

Component Testing with Cypress

Component testing focuses on individual components, ensuring they work correctly in isolation.

Cypress with Vue

Next step is create configuration file and you just continue with that so configuration file added in your project directory.

Mounting Components:

Code

    import Todo from './Todo.vue';
    it('mounts', () => {
        cy.mount(Todo);
    });
            

Passing Data:

Code

    cy.mount(Todo, {
        props: {
            msg: 'Cypress with Vue',
        },
    });
            

Using Slots:

Code

    import DefaultSlot from './DefaultSlot.vue';

    describe('<DefaultSlot />', () => {
        it('renders', () => {
        cy.mount(DefaultSlot, {
            slots: {
            default: 'Default slot testing!',
            },
        });
        cy.get('div.content').should('have.text', 'Default slot testing!');
        });
    });
            

Organizing Cypress Tests

Organize your Cypress tests into a clear folder structure:

  • e2e/: End-to-end test files
  • component/: Component-level test files
  • fixtures/: Test data files
  • support/: Configuration options and helper functions
  • screenshots/: Captured screenshots during tests
  • video/: Video recordings of test runs
  • downloads/: Downloaded files during tests

Cypress Configuration Files

Configure Cypress settings in cypress.config.js:

Code

    import { defineConfig } from 'cypress';

    export default defineConfig({
        component: {
        devServer: {
            framework: 'vue',
            bundler: 'vite',
        },
        specPattern: ['src/**/__tests__/*.{cy,spec}.{js,ts,jsx,tsx}', 
        'cypress/components/**/*.{js,jsx,ts,tsx}'],
        },
        e2e: {
        experimentalStudio: true,
        baseUrl: 'http://localhost:5173',
        setupNodeEvents(on, config) {},
        },
    });
            

Basic Cypress Commands

cy.visit(url): Visits a specific URL.

EX:

Code

    cy.visit('http://localhost:5173')
            

cy.get(selector): Gets an element using a selector.

EX:

Code

    cy.get('.selector')
            

cy.type(text): Types text into an input field.

EX:

Code

    cy.get('input[name="username"]').type('exampleUser')
            

cy.click(): Clicks on an element.

EX:

Code

    cy.get('.button').click()
            

cy.should(assertion): Makes assertions about the state of your application.

Common assertions:

EX:

Code

    cy.should('be.visible')
            

EX:

Code

    cy.should('have.text', 'expected text')
            

EX:

Code

    cy.should('contain', 'partial text')
            

Code

    cy.get('.item').should('have.length', 3)
            

cy.intercept(arguments): Spies and stubs network requests and responses.

EX:

Code

    cy.intercept('POST', '/users*', { statusCode: 201, body: {name: 'john duo'} })
            

Advanced Features

  • Cypress Studio: Generate tests interactively through a graphical interface.
  • Cypress Cloud: Advanced features like parallel test execution, flake detection, and insights into test runs for efficient management and scaling of your testing infrastructure.

By following these guidelines, you can leverage Cypress to its full potential, ensuring your Vue.js applications are robust, reliable, and ready for production.

To optimize your Vue projects with Cypress, trust our skilled developers at Zignuts. Our experts can enhance your application's performance and testing. Learn more about our Vue.js development services and hire top talented Vue.js Developers today.

card user img
Twitter iconLinked icon

Zignuts Technolab delivers future-ready tech solutions and keeps you updated with the latest innovations through our blogs. Read, learn, and share!

300+ startups trusted us. You can be next.

Let’s turn your vision into a winning product.

Valid number
Claim My Spot!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
download ready
Thank You
Your submission has been received.
We will be in touch and contact you soon!
crossmessage

Our Latest Blogs

View All Blogs