DEV Community

Cover image for Testing the Redux Store using Cypress in Next.js (TypeScript)
Rashid Shamloo
Rashid Shamloo

Posted on

2 1

Testing the Redux Store using Cypress in Next.js (TypeScript)

This is a quick step-by-step guide for setting up Redux (Toolkit) testing using Cypress. I assume you already know how to install, set up, and use Redux (Toolkit) and Cypress separately.

1. Accessing the Redux Store

You can't directly import and interact with your Redux store inside your test spec file. You first need to add it to the window in your store.ts file. You can do it in two ways:

- Adding the store to the window itself

This is not recommended because it can cause conflicts.

declare global {
  interface Window {
    Cypress?: Cypress.Cypress;
    store?: typeof store;
  }
}

if (typeof window !== 'undefined' && window.Cypress) {
  window.store = store;
}
Enter fullscreen mode Exit fullscreen mode

- Adding the store to window.Cypress

Recommended

interface CypressWithStore extends Cypress.Cypress {
  store?: typeof store;
}

declare global {
  interface Window {
    Cypress?: CypressWithStore;
  }
}

if (typeof window !== 'undefined' && window.Cypress) {
  window.Cypress.store = store;
}
Enter fullscreen mode Exit fullscreen mode

2. Dispatching Actions

You can use invoke('dispatch', action) to dispatch actions to the store:

cy.window()
.its('Cypress')
.its('store')
.invoke('dispatch', SomeAction(payload));
Enter fullscreen mode Exit fullscreen mode

3. Reading the State

You can use invoke('getState') to read the state:

cy.window()
.its('Cypress')
.its('store')
.invoke('getState')
.its('stateVariable')
.should(assertion);
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay