0

I am recently new in cypress, and I am dealing with a complex test. In this test I have to bring the urls that are hosted on Contentful, and verify that the content page does not come with an error message. The problem is in the line const data= new Uint8Array(response.body);, which brings me the empty array (response comes with data) Any suggestion helps me a lot to solve this problem

import { getPagesFromContentful } from '../../support/getPagesFromContentful';
import '../../support/commands';

describe('Mi prueba', () => {
     beforeEach(() => {
    cy.clearLocalStorage(); // Limpiar el almacenamiento local
    cy.clearCookies();
  });
 
  it('prueba pagina parte 1', () => {
    getPagesFromContentful().then((response) => {
      cy.wrap(response).as('pagesUrls');
      console.log(response);
      const errores = [];

      cy.get('@pagesUrls').each((url) => {
        cy.request({
          url: url,
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
          failOnStatusCode: false, // No detener la prueba en caso de error de estado
          responseType: 'arraybuffer',
        }).then((response) => {
          console.log('hola', response);
          const body = JSON.parse(response.body);
          console.log(body);

          // Realizar las comprobaciones en el contenido
          try {
            cy.wrap(body).should('not.contain', 'error-page');
          } catch (error) {
            const errorMensaje = `Error en la posición ${url}: ${
              error.message
            }\n\nContenido del arreglo: ${JSON.stringify(body)}`;
            //debugger;
            errores.push(errorMensaje);
            cy.log(errorMensaje);
            //debugger;
          }
        });
      });
      if (errores.length > 0) {
        // Si hay errores, mostrarlos y fallar el test
        const errorMessage = `Se encontraron ${errores.length}                     errores:\n\n${errores.join('\n\n')}`;
        cy.log(errorMessage);
        throw new Error(errorMessage);
      }
    });
  });
});

1 Answers1

0

This is my first answer here, so please be gentle :-)

I'm not sure if I got your problem correctly, but what I understood from learning and working with Cypress is that it is super fast in assertions, and that often equals undefined values because is skipping to the next step before receiving all responses.

My suggestion would be to be sure that all the requests are completed before starting with checking if there are errors. You could do that using a Promise:

...
const requests = [];

cy.get('@pagesUrls').each((url) => {
      const requestPromise = cy
        .request({
         ...
         )};
     //adding the single promise to promises array
        requests.push(requestPromise);
    });

//wait for all the requests to complete
Promise.all(requests)
     .then(() => {
        if (errores.length > 0) {
           ...
          })
     .catch((error) => {
       //return any error that happens during the requests
       console.error('Error:', error);
      });


Let me know if it helps :D!

svarion0
  • 1
  • 1
  • `cy.request( )` does not return a promise, so `Promise.all(requests)` (probably) won't work. – Otto Jul 01 '23 at 09:31