1

I need to inject a value (dispatch an action) in my Angular Store in order to make my Cypress e2e tests to work. Indeed, I need my store to contain { isLoggedIn : true } to access any page in the app, otherwise user is redirected to the login page.
I found a similar question here Cypress - programmatically manipulating Angular/NGRX app, but the answer does not seem to work in my case.
I always get the error: "cy.its() waited for the specified property store to exist, but it never did."
None of the console.log are printed in the console of cypress when running the test.
Here is my code in app.component.ts

export interface IWindowCypress {
  store: Store;
  Cypress: unknown;
}

@Component({
  selector: 'my-root',
  templateUrl: './app.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
  constructor(protected store: Store) {
    const windowWithStore: IWindowCypress = window as unknown as IWindowCypress;
    console.log('AppComponent');
    if (windowWithStore.Cypress) {
      console.log('save store');
      windowWithStore.store = store;
    }
  }
}

Here is my cypress test

describe('ContactListComponent', () => {
  before(() => {
    cy.window().its('store').invoke('dispatch', { type: '[User Effect] Load user success', user: { isLoggedIn : true } });
  });

// some tests

So I wonder what I am missing here or what I am doing wrong. Can anyone help ? Thank you !
PS: If I run my app with npm run start I have "AppComponent" printed in the console

TCH
  • 421
  • 1
  • 6
  • 25

1 Answers1

4

This difference between your code and the reference question is

window.store = this.store;   // referring to component instance store property

I'm not sure why the injected store isn't working, but try

export class AppComponent {
  constructor(protected store: Store) {
    const windowWithStore: IWindowCypress = window as unknown as IWindowCypress;
    if (windowWithStore.Cypress) {
      windowWithStore.store = this.store;
    }
  }
}

You might also want the interface properties to be optional since they are not always present.

export interface IWindowCypress {
  store?: Store;
  Cypress?: unknown;
}
Paolo
  • 3,530
  • 7
  • 21