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

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;
}

- 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;
}

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));

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);