Error encountered during Jasmine unit testing for the ng-redux @select directive

Here is a snippet from my component.ts file:

import { Component, OnInit } from '@angular/core';
import { select } from 'ng2-redux';
import { Observable } from 'rxjs/Observable';
import { PersonalDetailsComponent } from '../personal-details/personal-details.component'

@Component({
  selector: 'app-profile-details',
  templateUrl: './profile-details.component.html'
})
export class ProfileDetailsComponent implements OnInit {

  @select(['customerData', 'personalDetails'])personalDetails:Observable<object>; //<------if i comment out @select statement, then the tests work 
  @select(['loading']) loading: Observable<boolean>;//<------if i comment out @select statement, then the tests work 

  constructor() { }

  ngOnInit() { }

}

Below is how my jasmine test for the ProfileDetailsComponent looks like:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NgRedux, select } from 'ng2-redux';
import { ProfileDetailsComponent } from './profile-details.component';
import { customerData } from '../data/customerProfileDataMock';
import { PersonalDetailsComponent } from '../personal-details/personal-details.component'
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';

class RouterStub { navigate(params) { } }
class MockSelect { }
class MockObservable<T> {}
class NgReduxStub {
  constructor() { }
  dispatch = () => undefined;
  getState = () => { return customerData; };
  subscribe = () => undefined;
}

describe('ProfileDetailsComponent', () => {
  let component: ProfileDetailsComponent;
  let fixture: ComponentFixture<ProfileDetailsComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ProfileDetailsComponent, PersonalDetailsComponent],
      providers: [
        { provide: Router, useClass: RouterStub },
        { provide: select, useClass: MockSelect },
        { provide: NgRedux, useClass: NgReduxStub },
        { provide: Observable, useClass: MockObservable }
      ],
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ProfileDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create the profile details page', () => {
    expect(component).toBeTruthy();
  });

});

Despite setting up mocks in the test, I'm encountering an issue where the @select statement is not being mocked correctly. This leads to an error when running the tests using the command 'ng test':

TypeError: ng_redux_1.NgRedux.instance is undefined in src/test.ts

Answer №1

It appears that there may have been some changes in the package you are using. I observed that ng2-redux on npm (https://www.npmjs.com/package/ng2-redux) now directs to the github repository https://github.com/angular-redux/store. This could indicate a merging of branches.

If this is the case, I recommend updating your package. A new feature called MockNgRedux has been recently introduced, which you can incorporate into your tests as follows:

import { NgReduxTestingModule, MockNgRedux } from '@angular-redux/store/testing';

To integrate this into TestBed, use the following:

beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [
      NgReduxTestingModule,
    ],

You can utilize MockNgRedux to test components that utilize @select() by setting up values on specific selectors like this:

const stub = MockNgRedux.getSelectorStub(selector);
stub.next(values);
stub.complete();

It's worth noting that the methods are static and do not require an instance of MockNgRedux.

Remember to reset the mock store between tests:

beforeEach(() => {
  MockNgRedux.reset();
});

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

Angular is notifying that an unused expression was found where it was expecting an assignment or function call

Currently, I am working on creating a registration form in Angular. My goal is to verify if the User's username exists and then assign that value to the object if it is not null. loadData(data: User) { data.username && (this.registrationD ...

Response from Mongoose Populate shows empty results

Within my MongoDB, there exist two collections: Users and Contacts. In my project structure, I have defined two models named User and Contact. Each User references an array of contacts, with each contact containing a property called owner that stores the u ...

Hiding a div after three clicks using HTML

What is the best way to hide a div tag containing an input tag after clicking on the input tag three times using HTML and angular? ...

Vue: Storing selected list values in an array

I am working on a Vue application where I need to select two elements from a list component and place them inside an array. Currently, I have my list set up with selection functionality thanks to Vuetify. I have bound the selected items to an array using v ...

Updating an Angular 4 component based on the current URL or the state of another component

The main objective The primary goal here is to click on one of the top users displayed on the left and have the details about that user refreshed on the right side. This requires establishing a communication link between these two components. What we are ...

Obtain an Angular2/4 Carousel component through a service in order to create a seamless loop

I am currently working on implementing a carousel in Angular. While it is not complicated to include slide images directly in the html, I am interested in fetching them from an array stored in a service for more dynamic functionality. Here is a snippet of ...

Is it possible for FormArray to return null?

Hello there. I've attempted various methods, but none of them seem to be effective. Currently, I am working on this task where I need to start a formArray for emails. email: [testestest] However, what I have is: email: [testestest] I'm encoun ...

The function column.getHeaderGroupProps does not seem to be available

Struggling with the initial setup of react-table with typescript. I keep encountering an error related to the data passed into my table function: column.getHeaderGroupProps is not a function TypeError: column.getHeaderGroupProps is not a function at ht ...

Should front-end and back-end share Typescript data modeling through classes or interfaces?

I'm currently exploring the best approach to share the same data types between the client (React) and the server (Express + Socket.IO). Within my game, there are various rooms each storing the current status, such as: class GameRoom { players: P ...

What is the process for integrating TypeScript compiling into a JavaScript application?

My project includes a build.js file that is responsible for building the project. It has two main objectives: Compile .ts files and store them in a new directory. Create an asar archive containing the compiled files. Since typescript (or tsc) is availabl ...

What is the correct way to set up a custom class instance with specific parameters at the top level?

Is it possible to utilize the defineString(), defineInt, ... functions within a top-level custom class constructor? defineString() returns a StringParam object which has a value() method. I am looking to use parameterized configuration to initialize an in ...

Seeking a quick conversion method for transforming x or x[] into x[] in a single line of code

Is there a concise TypeScript one-liner that can replace the arrayOrMemberToArray function below? function arrayOrMemberToArray<T>(input: T | T[]): T[] { if(Arrary.isArray(input)) return input return [input] } Trying to cram this logic into a te ...

When I attempt to add a todo item by clicking, the Url value is displayed as "undefined"

I am facing an issue with my household app where, upon clicking the button to navigate to the addtodo page, the URL specific to the user's house is getting lost. This results in the todolist being stored as undefined on Firebase instead of under the c ...

Can TypeScript provide a method for verifying infinite levels of nested arrays within a type?

Check out this example The concept behind this is having a type that can either be a single object or an array of objects. type SingleOrArray<T> = T | T[]; The structure in question looks like this: const area: ItemArea = [ { name: 'test1& ...

Tips for transforming alphanumeric characters into value ranges using Typescript

myArray = ["AB01","AB02","AB03","AB04","AB11","BC12","BC13", "SB33"]; // code snippet to create expected string: "AB01-AB04, AB11, BC12-BC13, SB33" The array contains combinations of one or two letter characters followed by two or three digits. Examples ...

The object is classified as 'undetermined' (2571) upon implementation of map() function

Despite conducting a thorough search about this error online, I still haven't been able to find a solution. Let's jump into an example with data that looks like this: const earthData = { distanceFromSun: 149280000, continents: { asia: {a ...

Navigate to the middle of a DIV container in Angular 7

Is there a way to programmatically scroll to the center of my element on both the Y and X axes when a specific function is executed? My HTML structure includes the following (I am aiming to scroll to the middle of #viewport): </div> <div # ...

Creating a dynamic component in Angular using the ng-template approach

Exploring Components using ng-template @Component({ template: ` <div>Welcome to the Component!</div> <ng-template #contentTemplate> <div>This is the template content</div> </ng-template> `, }) expo ...

The selectors in NgRx store are failing to retrieve data from the main global store

As I delve into the world of ngrx, I find myself struggling to fully understand and implement it effectively within my application. Recently, I integrated ngrx version 8.3 into my project in hopes of organizing my state management efficiently. My goal is ...

Exploring techniques to retrieve data from Json Array in Angular using Firebase documentation

this.currentUser$=this.afs.doc('users/'+this.authState.uid).valueChanges().pipe(); When I include it in my component.html file like this: {{ currentUser$|async|json}} The output I get is as follows: { "photoUrl": "", &qu ...