0

I'm trying to test whether my component is calling the ngrx dispatch method. Here are the relevant parts of the component:

  ngOnInit(): void {
    this.setCurrentUser();
  }

  setCurrentUser() {
    const storedUser = localStorage.getItem('user');
    this.localStorageUser = storedUser !== null ? JSON.parse(storedUser) : null;    
    if (this.localStorageUser) {  
      console.log("Test"); // THIS IS BEING CALLED
      this.accountStore.dispatch(AccountAppCompActions.setLoggedOnUser({ user: this.localStorageUser }));
    }
  }

These are the relevant bits from my Cypress tests:

   let store: MockStore;
   let initialState: { account: { loggedOnUser: User | null }};
   const testUser = new User();
   testUser.username = "Mr Test";
   testUser.email = "Test@gmail.com";

    const mountComponent = () => {
        cy.mount(AppComponent, setupCypressConfig<AppComponent>({
            providers: [
                provideMockStore({ initialState }),
            ]
        }));
    };
    
    beforeEach(() => {
        mountComponent();
        store = createMockStore({initialState});
    });
    
    it('should dispatch setLoggedOnUser action when user found in local storage', () => {
        cy.spy(store, 'dispatch').as('mockStore-dispatch-method');
        window.localStorage.setItem('user', JSON.stringify(testUser));
        cy.get('@mockStore-dispatch-method').should('have.been.called');
    });

The test keeps failing with the message:

expected mockStore-dispatch-method to have been called at least once, but it was never called

I can't understand why the test is failing?

Pablo52
  • 41
  • 6

0 Answers0