Cypress is an automated end-to-end testing framework that enables developers to write tests for their web applications. It can test anything that runs in a browser, whether it’s a single-page application written in Angular, Vue, or a server-rendered application.
Cypress makes setting up, writing, running, and debugging tests easy.
Cypress supports various types of testing:
- End-to-End Testing (E2E)
- Integration Testing
- Unit Testing
Here is how it can be used for testing in JavaScript:
1. Install Cypress:
You can add Cypress to your project by using npm or yarn:
For npm:
```
npm install cypress —save-dev
```
For yarn:
```
yarn add cypress —dev
```
1. Add Cypress scripts to your package.json file:
```
{
“scripts”: {
“cypress:open”: “cypress open“
}
}
```
1. Running Cypress:
You can start writing tests by opening Cypress. This could be done by running the cypress open command in CLI:
```
npm run cypress:open
```
1. Creating a Cypress test:
Test files are located in “cypress/integration”. You can create a “.spec.js” file for each feature you’re going to test.
Here is a simple example:
```
describe(‘My Test Suite’, () => {
it(‘Visits my webpage’, () => {
cy.visit(‘http://localhost:3000’) // Edit this URL to point to your application
cy.get(‘#my-element’).should(‘contain’, ‘Hello World’) // Test whether #my-element contains the text ‘Hello World‘
})
})
```
This script will visit your local application and check if an element with the ID “my-element” contains the text ‘Hello World’.
1. Running the test:
Go back to the terminal and you should see your new test appearing in the Cypress UI. Click on its name to run the test.
You will see the test results on the screen, alongside any visual changes on your local development server.
Cypress has a fluent and chainable API that’s easy to read and understand. It also has excellent error messages, powerful debugging capabilities, and fantastic documentation.