Error message when testing Angular 6 ngrx store: Unable to retrieve ids from undefined variable

I'm currently in the process of testing a component that has received a Store injection. However, I am encountering an issue where the test is failing and displaying an error message: "Cannot read property 'ids' of undefined"

Test:

 const initialState = {
    quoteInfo: {
        quoteLoaded: true,
        ids: [0],
        entities: {
            '0': {
                id: 0,
                quoteId: 'string',
                quoteStatus: 0,
                reference: 'ref01',
            }
        }
    },
    quoteSettings: {
        quoteSettingsReceived: true,
        ids: [1],
        entities: {
          '1': {
            id: 1,
            status: 0,
            customer: 'string',
            customerId: 'cus01',
            carrier: 'car01',
            contact: 'contact01',
            contactId: 'c01',
            priceCategory: 'vip',
            priceCategoryId: 'pr1',
            creationDate: null,
            expirationDate: null,
            deliveryDate: null,
            currency: null,
            currencyId: null,
            paymentDescription: 'pay desc',
            tax: 0,
            comments: 'comments',
            shippingAddress: null,
            billingAddress: null
          }
        }
    }
  };

Test beforeEach:

  beforeEach( async(() => {
    TestBed.configureTestingModule({
      declarations: [GeneralComponent],
      imports: [
        BrowserAnimationsModule,
        HttpClientModule,
        StoreModule.forRoot({ feature: combineReducers({quoteSettings: settingsReducer, quoteInfo: infoReducer }, initialState)}),
      ],
      providers: [
      ]
    }).compileComponents();
  }));

The error occurs during the initialization of the component, where the code looks like this:

 ngOnInit() {
    this.randomObservable$ = this._store.pipe(select(randomSelector));
  }

Random Selector

export const randomFeatureSelector= createFeatureSelector<RandomState>('random');
export const randomSelector = createSelector(
  randomFeatureSelector, // this is null
  fromRandomReducer.selectAll
);

Answer №1

The issue stemmed from the html code where I attempted to use the observable directly from the selector, resulting in an error if the store had not been initialized yet.

Answer №2

My go-to method for mocking a Store is to utilize the power of BehaviorSubject from the rx.js library:

let mockStore;
beforeEach( async(() => {
 mockStore = new BehaviorSubject(initialState);
 TestBed.configureTestingModule({
  declarations: [CustomComponent],
  imports: [
    BrowserAnimationsModule,
    HttpClientModule
  ],
  providers: [
  {provide: Store, useValue: mockStore}
  ]
}).compileComponents();

}));

...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Redirect to login not working in Angular auth guard

Seeking assistance with troubleshooting an issue within my app. I am attempting to implement a feature where, if the user is not logged in and tries to access any URL of the app, they should be redirected to the login page. I have set up an auth guard, bu ...

How do I convert the ImagePicker type to Base64 in Ionic Capacitor?

I am currently developing an app using Ionic (Angular-based) along with Capacitor Plugins, specifically the Camera Plugin. The main feature I am working on involves allowing users to choose up to 5 images from their gallery. To accomplish this, I have impl ...

The Map<> type does not seem to offer autofill suggestions for union arrays

Can anyone explain why TypeScript isn't providing autofill suggestions for "foo" or "bar" when typing elements into an empty array in the code snippet below? const map: Map<string, ('foo' | 'bar')[]> = new Map([ ['hell ...

Angular throws an error when attempting to use localStorage as it is not defined in the environment

Encountering an issue while running this code, as the error message "localStorage is not defined" keeps popping up. Additionally, when it comes to todos != Todo[], why can't we simply set it to null instead of using the exclamation mark? import { Comp ...

Struggling to retrieve the value of a variable from a service in Angular

In my application, I've implemented a cookie checking service to monitor the status of my cookie consent popup: @Injectable() export class CookieCheckService implements OnInit, OnDestroy { public hasConsented = false; private cookieStatusChangeSu ...

Deselect radio button in Angular 7 using Bootstrap 4 styling

Seeking assistance with using Angular 7 and Bootstrap 4 to create radio buttons that can toggle on and off. I came across a solution here. Check out my current method. Currently, I am able to toggle the buttons, however, I now face a new dilemma. I want e ...

Adding isAuth and access_token to express-session in a Node.js web application is a straightforward

Initially, I set the request type to be "any", but upon realizing that it should not be "any" or "Request", I have decided to extend express-session in order to create a custom session type. How can I achieve this and incorporate the specified informatio ...

Issue with Child Component Loading Once CUSTOM_ELEMENTS_SCHEMA is Added to App Module

One of my components, known as HostComponent, works perfectly fine when set as the startup component in my application. However, I decided to create a new module called AppModule and nested the host component within the app component: import { Component, ...

Angular: Creating an input field with preset value that is immutable

I am a beginner with angular and I have been working on this code snippet: <mat-form-field appearance="outline" class="col-30" id="mat-identifier"> <mat-label> {{'columns.dashboard.identifier' | ...

Newbie seeking help with Angular Services

I'm struggling to avoid duplicating code by using a service. How can I refactor this into a service and then utilize it in the component? Any assistance would be greatly appreciated. function navigateToLink(myRecords) { this.targetLink = this.data.l ...

React-router-dom TypeScript error when defining the type of the prop parameter in the loader

I'm having trouble with the params prop in the loader prop within the routes. I've defined the params in TypeScript, but I'm getting errors that I don't understand. Any help would be appreciated, thanks in advance. I tried to use the Cu ...

Tips for transferring a column in an array to an object field within an array

I have a piece of code where I need to pass values from the 'dataList' array into this.data object's 'labels' and 'datasets'-> data. When I try to directly set the values, I get an undefined result. So I created a var ...

Tips for successfully sending an interface to a generic function

Is there a way to pass an interface as a type to a generic function? I anticipate that the generic function will be expanded in the future. Perhaps the current code is not suitable for my problem? This piece of code is being duplicated across multiple fil ...

Disabling a specific tab in an array of tabs using Angular and Typescript

Displayed below are 5 tabs that can be clicked by the user. My goal is to disable tabs 2 and 3, meaning that the tab names will still be visible but users will not be able to click on them. I attempted to set the tabs to active: false in the TypeScript fi ...

Oops! Looks like the Angular router outlet name is not matching any routes

I am currently working with Angular 6 and I would like to implement a modal using routing. I have set up a router outlet named "modal", but when I try to navigate to the route of the modal, an error message is displayed: Error: Uncaught (in promise): Er ...

Exploring the depths of a nested object by traversing through an array of its

Trying to iterate through a nested object structure with Angular TS: { "stringKey1": { "child": [ { "stringKey2": { "child": [] ...

Changing the value of an object in Angular can be achieved by utilizing the two

I have a service with the following methods: getLastStatus(id): Observable<string> { let url_detail = this.apiurl + `/${id}`; return this.http.get<any>(url_detail, this.httpOptions).pipe( map(data => { ...

Elevate your Material UI Avatar with an added level of

Attempting to give a MUI Avatar component some elevation or shadow according to the documentation provided here. <Avatar alt="Cindy Baker" src="/static/images/avatar/3.jpg" /> Enclosing the Avatar within a paper or Card element increases the size o ...

Utilizing Angular 9's Http Interceptor to Obtain an AWS Access Token

I've been trying to implement AWS access token in an Angular HTTP interceptor by following this guide. However, my code seems to be caught in an infinite loop and I keep receiving a net::ERR_INSUFFICIENT_RESOURCES error. When I console.log the token ...

Choose does not showcase the updated value

My form contains a form control for currency selection Each currency object has the properties {id: string; symbol: string}; Upon initialization, the currency select component loops through an array of currencies; After meeting a specific condition, I need ...