How to load the web app one time for all the tests in Cypress?

39 Views Asked by At

My web app lives on http://localhost:1234/. Each time it loads, it needs to read 1000+ JSON files to populate the needed information. Is there anyway, we can avoid reinitializing the web app for each test.

I have about 100 tests and it is very time consuming to run all of them because each test has to reload the web app. e.g: cy.visit('/')

I saw on Cypress website that we can use cy.session() https://docs.cypress.io/api/commands/session#Where-to-call-cysession

However, I have issue of getting it to work since I still need to specify the path that the test starts. Thus, the web app will read 1000+ JSON files again. Otherwise, I will get a blank screen. Did I do it correctly? or cy.session() is not the correct solution.

// in commands.js
Cypress.Commands.add('initialize', () => {
  cy.session('init', () => {
    cy.visit('/')
   
  })
})

// in test1.spec.js
beforeEach(() => {
  cy.initialize()

})

// Failed Test
it('Check the customer logo if exist 1', () => {
  cy.get('#customer-logo') // never found because the screen is blank 
 
})

// Success Test
it('Check the customer logo if exist 2', () => {
  cy.visit('/') 
  cy.get('`your text`#customer-logo') // able to find the div 

 
})

1

There are 1 best solutions below

0
Jen.Wohlleben On

cy.session() only caches cookies, localstorage, and session storage. Using cy.visit() inside cy.session() doesn't cache the page itself.

Since the cache bypasses the setup function for 2nd, 3rd, etc tests, you will not be navigated to the correct URL, hence the blank page (i.e `about/blank' staring page with the Cypress logo).


Turning off test isolation is the simplest option,

// cypress.config.js
const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    testIsolation: false,
  },
})

But if you feel that would compromise your tests, you may be able use intercept and fixture to speed up the page load.

This assumes you don't use server side rendering in some format, and the json data is accessed from an API.

The code is roughly as follows:

// create a fixture from the aggregation of json files, keyed by API url

beforeEach(() => {

  cy.fixture('apiFixture').then(data => {
    // fixture command is caching the data, so it's only read once

    cy.intercept('**/api/**/*', (req) => {
      req.reply(data[req.url])
    })
  })

  cy.visit('/')
})