Day 14 of 100daysofcode : Cypress Setup
Setting up Cypress for automation testing is straightforward and involves a few steps. Below is a detailed guide:
Step 1: Install Node.js
Cypress requires Node.js to run. If you don’t have Node.js installed:
- Download it from Node.js official website.
- Install it by following the prompts.
Step 2: Create a Project Directory
- Open your terminal or command prompt.
- Create a new project folder for your automation tests:
mkdir cypress-automation cd cypress-automation - Initialize a new Node.js project:
This creates anpm init -ypackage.jsonfile to manage your project dependencies.
Step 3: Install Cypress
Run the following command to install Cypress:
npm install cypress --save-dev
This will add Cypress as a development dependency in your project.
Step 4: Open Cypress
After installation, you can open Cypress using the following command:
npx cypress open
This command will:
- Launch the Cypress Test Runner.
- Create a default folder structure (
cypress/) in your project directory:cypress/e2e: Place your test files here.cypress/fixtures: Store static data (e.g., JSON files) for your tests.cypress/support: Add custom commands or reusable logic here.
Step 5: Write Your First Test
- Inside the
cypress/e2efolder, create a new test file, for example:touch cypress/e2e/sample_test.cy.js - Add a simple test in the file:
describe('My First Test', () => { it('Visits the Cypress website', () => { cy.visit('https://www.cypress.io'); cy.contains('Features').click(); cy.url().should('include', '/features'); }); });
Step 6: Run Tests
- Start Cypress Test Runner:
npx cypress open - Select the test file you created (
sample_test.cy.js) and run it.
Step 7: Configure Cypress (Optional)
You can customize Cypress settings in the cypress.config.js or cypress.config.ts file created in your project root. For example, to set a base URL for your tests:
const { defineConfig } = require('cypress');
module.exports = defineConfig({
e2e: {
baseUrl: 'https://example.com',
setupNodeEvents(on, config) {
// implement node event listeners here
},
},
});
Step 8: Add Cypress to Scripts (Optional)
To make running tests easier, add Cypress commands to your package.json scripts:
"scripts": {
"cypress:open": "cypress open",
"cypress:run": "cypress run"
}
Now, you can run Cypress with:
npm run cypress:open: Opens the Test Runner.npm run cypress:run: Runs tests in headless mode.
Step 9: Integrate Cypress with CI/CD (Optional)
To run Cypress tests in CI/CD pipelines, you can use the cypress run command. Add this step to your CI/CD configuration file (e.g., GitHub Actions, Jenkins, or CircleCI).
Step 10: Explore More Features
- Assertions: Use Chai.js assertions built into Cypress.
- Fixtures: Load external test data using
cy.fixture(). - Custom Commands: Add reusable logic in
cypress/support/commands.js.
For more details, visit the Cypress Documentation.