Tips on implementing local storage in cypress

I am encountering an issue with a simple test

describe('Page Test', () => {
  it('button has "contact-next-disabled" class', () => {
    cy.get('.contact-next-disabled')
  })
})

Upon running the test, cypress displays an error message

  34 | useEffect(() => {
  35 |   const _contact = getLocalStorage()
> 36 |   if (!_contact.categories.length && !_contact.categoryNameEtc) {
     |                ^
  37 |     PGToaster.showDanger('Please select a category.')
  38 |     router.push('/contact/a-type')
  39 |   }

The function getLocalStorage that I am using is located in a separate file from the one being tested

export const getLocalStorage = () => {
  const contact = JSON.parse(window.localStorage.getItem('contact'))
  return contact
}

This function works alongside my setLocalStorage function

export const setLocalStorage = (contact) => {
  const _contact = getLocalStorage()
  const updateContact = {
    ..._contact,
    ...contact
  }
  window.localStorage.setItem('contact', JSON.stringify(updateContact))
}

Instead of modifying my code, I attempted to resolve the error by making a minor alteration in the test script:

if (!_contact?.categories.length && !_contact?.categoryNameEtc)

By implementing this change, the error disappeared. However, I seek a solution to set local storage directly in my cypress test without having to revise my existing code. Is there a way to achieve this?

Answer №1

As per the documentation found on cy.clearLocalStorage()

Cypress automatically executes this command before each test in order to prevent sharing of state across tests. It is recommended not to use this command unless it is necessary to clear localStorage within a singular test.

You have the option to configure your tests using hooks:

before(() => {
  // set localStorage
})

Alternatively, you can utilize a plugin such as cypress-localstorage-commands to maintain localStorage integrity between Cypress tests.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to bring GIFs into NextJS

I am currently working on my portfolio website using Nextjs and I would like to incorporate gifs into the site. However, I have been struggling to figure out how to do so. Below is the code that I have been working with: https://i.stack.imgur.com/zjoiD.pn ...

Determining if the state in React has been altered

State containing client information is stored here const { info, setInfo, onPostInfoChanges } = useContext(ClientInfos); Below is a function that sends new info data to the server using POST or PUT requests const onSubmitHandler = async (model) => { ...

Error in serving static files in React build through Express server

Hello everyone, I am fairly new to react and facing some challenges while trying to convert my MEAN stack app into an express and reactjs application. The main issue I am encountering is related to getting my build files to load correctly. It seems like my ...

Utilizing Socket technology in combination with Sails JS and React JS

Currently, I have a live bidding system in place. On the bidding page, we display both the base price and current bid price of an item. Whenever a user updates the price of an item, I would like that new price to automatically reflect for all customers who ...

Having issues implementing CssBaseline

I referred to the solutions provided in this thread but encountered an error. TypeError: Object(...) is not a function const theme = createMuiTheme(); My goal is to apply default styles using <CssBaseline />. How can I achieve this? Below is my imp ...

Tips for building an extensive checklist page using React

Looking to create a webpage featuring an extensive checklist of 100 items that can be retrieved from and updated in a Firestore document. Here is my current strategy: // Here, we define states that store the checkbox values const [checkA, setCheckA] = u ...

Is your React Hook experiencing a delayed useEffect firing?

I've been experimenting with utilizing useEffect() within my React hook to ensure the state updates when the props change. However, I've noticed a delay where the useEffect is only triggered after clicking again on an element in my hook. As someo ...

Unable to modify the appbar's background hue

I recently came across this CodeSandbox project for a React Sidebar using Material UI, and I found it really useful. Now, I want to customize the background color of the appbar to #ffb74d. Despite trying several solutions that worked for me in other proje ...

We are unable to support Next.js server-side data fetching within `Suspense` boundaries at this time

I've been diving into the Next.js documentation to learn about implementing streaming server-rendering with React 18, and I came across a section on data fetching that caught my attention: The docs mention that data fetching within Suspense boundari ...

Ways to conditionally display a component in Next.js without the issue of caching CSS styles

I'm a newcomer to Next.js and I'm still trying to wrap my head around how the caching works. Let's take a look at this simplified example: An index page that displays either Test1 or Test2 components, based on whether the current minute is ...

The counterpart to Ruby's `.select{ |x| condition }` in Javascript/ React.js would be to

This javascript function in React.js utilizes a for loop to determine the opponent team: getOpponentTeam: function(playerTeamId){ var matches = this.state.matches; var player_team = this.state.player.team.name for (i in matches){ if (matches[i]. ...

When I attempt to run several promises simultaneously with Promise.All, I encounter an error

My code contains a series of promises, but they are not being executed as expected. Although the sequence is correct and functional, I have found that I need to utilize Promise.all in order for it to work properly. dataObj[0].pushScreen.map(item => { ...

Connecting the material-ui dropdown to a table

Is there a way to connect a react material-ui dropdown to a table? I am working on a project where I have a drop-down list containing countries and a table displaying country names and their corresponding capital cities. The goal is to update the table b ...

The specified property is not found in the type 'IntrinsicAttributes & IntrinsicClassAttributes<DatePicker> & Readonly<{ children?: ReactNode; }>'

As I delve into utilizing React along with TypeScript and Material-UI components, I encounter some errors. One such error message pops up like this: The Property 'openToYearSelection' is not found on type 'IntrinsicAttributes & Intr ...

Using React Material UI to pass an updated date throughout a multi-page application

I am encountering an issue with a multi-page form that includes a datetime picker from material UI. The problem is that the updated date is not being passed to the confirm page. I have tried various solutions, such as lifting the state, but so far, nothi ...

InputLabel from Material-UI obscures text content when the value of an Input field is set by a different Input

Currently, I am building a form using Material UI that consists of two sections: the user's shipping address and the billing address. Since these addresses are often the same, I have included a checkbox that automatically populates the billing address ...

Is there a way to remove the scrollbar from the menu created with react-burger-menu?

How can I remove the scroll bar from the menu created with react-burger-menu? Despite trying various CSS properties adjustments, I have not been able to achieve the desired effect. Here is an image of the open menu and the corresponding CSS: (https://i.st ...

I'm currently facing an issue where the Ionic styles are not displaying correctly within my Next.js application

I'm currently experiencing a problem where Ionic styles are not being applied to certain pages in my Next.js app. Despite working on the home page, the Ionic styles do not seem to be taking effect on the profile page. Any guidance on troubleshooting t ...

What potential factors could lead to an MUI Snackbar failing to produce the accurate class names?

I am facing an issue with displaying notifications on my Gatsby blog whenever the service worker updates. I am using a MUI Snackbar toast for this purpose. However, sometimes the styling of the toast is not applied correctly and it ends up looking like thi ...

Updating the count property of an object using setState in React

I have an array of integers ranging from 0 to 6 as my input. My goal is to create an object that gives the count of each number in the array. edition = [6, 6, 6, 1, 1, 2]; const [groupedEdition, setGroupedEdition] = useState([{"0": 0, "1&quo ...