Cypress, new kid on the block

Selenium tem sido minha ferramenta de escolha para automação de testes de UI por um bom tempo, e com razão. Ele foi o pioneiro e eu usei muito, mas recentemente tornei-me um fā do Cypress. Eu fiz um curso sobre Cypress (todos os exercícios podem ser encontrados no meu GH), e me convenci completamente de que ele apresenta uma alternativa mais eficiente e confiável.

Ao analisar as diferenças entre Selenium e Cypress, alguns fatores-chave se destacam. Selenium suporta várias linguagens incluindo Java, Python, C#, e outras enquanto Cypress é puramente JavaScript. Isso pode inicialmente parecer limitante, mas considerando que a maioria das aplicações web são agora baseadas em JavaScript, Cypress se torna uma escolha natural. Testes Selenium são executados fora do navegador enquanto Cypress roda diretamente dentro do navegador. Isso permite ao Cypress controlar todo o processo de automação, incluindo tráfego de rede, temporizadores e até mesmo o carregamento do código JavaScript. É este controle interno que promete estabilidade – uma promessa que o Selenium muitas vezes não consegue manter devido à suas dependências externas. A possibilidade de testar sua automação com opções de debugger no navegador é revolucionária, passo muito tempo entendendo meus scripts usando as abas do console, styles e rede, tenho certeza de que os desenvolvedores FE estão muito familiarizados com elas.

Cypress fornece uma API simples e fluida para interagir diretamente com o DOM, dê uma olhada:

describe('DOM Interactions Test', function() {
  it('Fills and submits a form', function() {
    cy.visit('https://www.example.com/form') // Cypress loads the webpage

    cy.get('input[name="firstName"]').type('John') // Cypress finds the input field firstName and types 'John' into it
    cy.get('input[name="lastName"]').type('Doe') // Cypress finds the input field lastName and types 'Doe' into it

    cy.get('button[type="submit"]').click() // Cypress clicks the submit button
  })
})

Compare com Selenium

WebDriver driver = new ChromeDriver();

driver.get("https://www.example.com/form"); // Open URL 

WebElement firstName = driver.findElement(By.name("firstName"));
firstName.sendKeys("John"); // Fill the firstName input

WebElement lastName = driver.findElement(By.name("lastName"));
lastName.sendKeys("Doe"); // Fill the lastName input

WebElement submitButton = driver.findElement(By.tagName("button")); 
submitButton.submit(); // Submit the form

Cypress permite que você interaja com seletores CSS!

Outra grande vantagem do Cypress é sua capacidade de lidar com operações assíncronas muito facilmente.

describe('Asynchronous Handling Test', function() {
  it('Waits for an element to be visible', function() {
    cy.visit('https://www.example.com') // Cypress loads the webpage

    cy.get('#asyncButton', { timeout: 10000 }) // Cypress waits for the element with id 'asyncButton' to become visible for up to 10 seconds
      .should('be.visible') // Asserts that the element should be visible
      .click() // Clicks the button once it's visible
  })
})

Lidar com API’s também é moleza:

describe("Todo List API Interaction", () => {
  // Define the base URL of your API
  const apiUrl = "https://example-api.com";

  beforeEach(() => {
    // Intercept the API call and load a JSON payload for the response
    cy.intercept("GET", `${apiUrl}/todos`, { fixture: "todos.json" }).as("getTodos");
    // Visit the application or a specific page where the API call is made
    cy.visit("/todo-list");
  });

  it("should fetch todos from the API and display them", () => {
    // Perform any actions that trigger the API call (e.g., click a button to fetch todos)
    cy.get("#fetch-todos-btn").click();

    // Wait for the API call to complete and the response to be displayed
    cy.wait("@getTodos");

    // Assert that the correct API endpoint was called and the response was handled properly
    cy.get(".todo-item").should("have.length", 3); // Assuming the response contains 3 todo items
  });
});

O que para mim é o grande atrativo é a minha ressalva: ao interagir a partir dos seletores CSS demanda que você seja cuidadoso ao escolher aqueles que têm menos chance de mudar e quebrar seus testes. Ainda assim, eu pretendo apenas usar Cypress para meus testes de UI.