How open connection with indexedDB for Cypress tests?

Viewed 968

I want to test my app that use indexedDB, and becouse of indexedDB my tests dont work, shoud I set up indexedDB for tests, and what correct way to do it.

My code

beforeEach(() => {

cy.request({
  method: 'POST',
  url :'http://localhost:3000/api/auth/login',
  body : {
    email: "name",
    password: "Passwprd"
  }
}).then(function(response) {

  loadScript('https://unpkg.com/localforage@1.5.5/dist/localforage.js').then(() => {
    
    window.indexedDB.open("testDB");
    
    localforage.config({
      driver: [localforage.INDEXEDDB],
      name: 'timesheetstestDBDB',
      storeName: 'testDB',
      version: '1.0',
    });
  })
   localforage.clear().then(() => {
    localforage.setItem('jobs', [{name: 'fdf'}]);
  });
}).then(()=>{
  cy.visit('http://localhost:3000/');
})

})

Component that I want to test use indexedDB requests for first component load, and I get error from cypress

Unhandled Rejection (OpenFailedError): UnknownError Internal error opening backing store for indexedDB.open.
 UnknownError: Internal error opening backing store for indexedDB.open.

I just want to now way to run tests, and open indexedDB connection for end to end cypress enviroment.

Normal queries to the server work fine in automatic mode, but on queries to the indexedDB tests fail, because in the environment that opens cypress indexedDB is not open.

I run my app as "cypress": "cypress open" in package.json file

enter image description here

1 Answers

The IndexedDB can be manipulated easily from Cypress by using localforage package. I'm using it to set things like the access_token inside the IndexedDB. Example:

import localforage from 'localforage';

const setAccessToken = (token: string) => {
  cy.log('Setting access token in IndexedDB');
  
  localforage.clear().then(() => {
    localforage.setItem('access_token', token);
  });

};

const generateAccessToken = (user: string, password: string) => {
  cy.log(`Generating new access token for: "${user}"`);
  cy.request('POST', `${Cypress.env('AUTH_SERVICE')}/login`, {
    login: user,
    password: password,
  }).its('body').then((res) => {
    setAccessToken(res.token);
    Cypress.env(`${user}_access_token`, res.token);
  });
};

Cypress.Commands.add("login", (user, password) => {
  if (Cypress.env(`${user}_access_token`)){
    cy.log(`Using cached access token for: "${user}"`);
    setAccessToken(Cypress.env(`${user}_access_token`))
  } else generateAccessToken(user, password);
});
Related