API testing with Cypress

Marie Drake, Principal Test Automation Engineer @ News UK

      https://www.mariedrake.com/         @mcruzdrake

Cypress recap

First Cypress Test

/// <reference types="cypress" />

describe('TodoApp', () => {
  it('should add a new todo successfully', () => {
    cy.visit('/');
    cy.get('.new-todo').as('addTodo');

    cy.get('@addTodo').type('do lunch and learn about Cypress {enter}');
    cy.get('@addTodo').type('have lunch {enter}');

    cy.get('.todo-list').find('li').should('have.length', 2);
    cy.getFirstTodoItem().should(
      'be.equal',
      'do lunch and learn about Cypress'
    );
  });
});

Cypress Test Runner

Now.. let's talk about API testing

API Testing Tools

  • Postman 
  • Newman
  • Supertest
  • Chai-HTTP
  • Rest Assured
  • Karate
  • ... and so much more

Title Text

What if we have 1 tool for both UI and API test automation?

Cypress to the rescue!

Cypress to the rescue!

Advantages of using Cypress to test your APIs

  • Built in support
  • Easy debugging (no more console logs!)
  • Revisit your API state via Cypress test runner - time travel
  • Skills easy to transfer since we are only using 1 tool
  • More buy-in to get developers involve with testing

cy.request()

cy.request(url)
cy.request(url, body)
cy.request(method, url)
cy.request(method, url, body)
cy.request(options)

First API test

/// <reference types="cypress" />

describe('Todo API', () => {
  it('returns a JSON data', () => {
    cy.request('/todos')
      .its('headers')
      .its('content-type')
      .should('include', 'application/json');
  });
});

Make a GET request to /todos API endpoint

Check its headers

On the header, check its content type

Assert that it returns a JSON data

Additional Resources

Any questions?