Mock out localStorage for component tests #16531
-
So far I'm having a blast using the cypress component tests. Made a little helper that allows me to test react context state. I have now made the state more persistent by saving it to local storage.. However that means I have to mock out Anybody got a good suggestion on how to go about this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
I'm a bit onfused - what are you asking for? Since everything runs in a real browser, localStorage should work as you'd expect. We do clear local storage before each test. I also found this community plugin which allows you to persist localStorage, but I am not sure what the main use cases are for this. |
Beta Was this translation helpful? Give feedback.
-
Sorry @lmiller1990 for keeping discussion alive when there is already an answer. Getting further with my tests I'm getting a It works fine in-real-life but the test fails.. it('moves previous purchase into cart', () => {
cy.setLocalStorage(localStoragePurchaseHistoryKey, previousPurchaseObjStr)
mount(
<>
<GlobalStyle />
<CartProvider>
<TheUsual />
</CartProvider>
</>
)
cy.getLocalStorage(localStorageCartKey).then((localStorageCart) => {
expect(localStorageCart).to.eq(null)
})
// cy.findByText("Ja tack").click()
// cy.getLocalStorage(localStorageCartKey).then((localStorageCart) => {
// expect(localStorageCart).to.eq(previousPurchaseObjStr)
// })
cy.wait(20000)
}) If manually click on "Ja tack" ("Yes please") it throws
When the onClick only reads from local storage, puts it into react state, which then by useEffect stores it to local storage const resetWithPreviousPurchase: TCartResetWithPreviousPurchase = () => {
const purchases: TCartItem[] = JSON.parse(localStorage.getItem(localStoragePurchaseHistoryKey))
cartItemsSet(purchases)
} React.useEffect(() => {
if (isInitialRender) {
isInitialRenderSet(false)
const cartItemsPersistent = JSON.parse(localStorage.getItem(localStorageCartKey))
if (cartItemsPersistent) {
cartItemsSet(cartItemsPersistent)
}
} else {
localStorage.setItem(localStorageCartKey, JSON.stringify(cartItems)) // 👈
}
}, [cartItems]) |
Beta Was this translation helpful? Give feedback.
I'm a bit onfused - what are you asking for? Since everything runs in a real browser, localStorage should work as you'd expect.
We do clear local storage before each test. I also found this community plugin which allows you to persist localStorage, but I am not sure what the main use cases are for this.