Cypress is a JavaScript-based end-to-end testing tool designed for modern web test automation. This developer-friendly tool operates directly in the browser using a DOM manipulation technique and enables front-end developers and QA engineers to write automated web tests while eliminating pain points.
Cypress is a highly preferred E2E testing framework and it provides us with a way to do API testing. For performing API testing, we don’t need any third-party dependency to perform this testing. We can just set up Cypress and perform API testing with it.
Setup: https://docs.cypress.io/guides/getting-started/installing-cypress
Basic Cypress commands:
// Cypress starts out with a blank slate for each test
// so we must tell it to visit our website with the `cy.visit()` command.
cy.visit('https://example.cypress.io/todo')
// We use the `cy.get()` command to get all elements that match the selector.
// Then, we use `should` to assert that there are two matched items,
// which are the two default items.
cy.get('.todo-list li').should('have.length', 2)
// We can go even further and check that the default todos each contain
// the correct text. We use the `first` and `last` functions
// to get just the first and last matched elements individually,
// and then perform an assertion with `should`.
cy.get('.todo-list li').first().should('have.text', 'Pay electric bill')
cy.get('.todo-list li').last().should('have.text', 'Walk the dog')
Note:
- e2e folder shall have all the *cy.js files
- Below line has to be present at the beginning of all the *cy.js files
/// <reference types="cypress" />
- Below is a sample cy.js file
/// <reference types="cypress" />
describe('example to-do app', () => {
beforeEach(() => {
// Cypress starts out with a blank slate for each test
// so we must tell it to visit our website with the `cy.visit()` command.
// Since we want to visit the same URL at the start of all our tests,
// we include it in our beforeEach function so that it runs before each test
cy.visit('https://example.cypress.io/todo')
})
it('displays two todo items by default', () => {
// We use the `cy.get()` command to get all elements that match the selector.
// Then, we use `should` to assert that there are two matched items,
// which are the two default items.
cy.get('.todo-list li').should('have.length', 2)
// We can go even further and check that the default todos each contain
// the correct text. We use the `first` and `last` functions
// to get just the first and last matched elements individually,
// and then perform an assertion with `should`.
cy.get('.todo-list li').first().should('have.text', 'Pay electric bill')
cy.get('.todo-list li').last().should('have.text', 'Walk the dog')
})
})
Reference: