"Utilizing provideMockStore in NgRx 8 for setting the state of a specific State Slice

I have been working on testing a smart component for my NgRx implementation, and the test setup looks like this:

describe( 'Component', () => {
  let store: MockStore<State>;

  beforeEach( async( () => {
    TestBed.configureTestingModule( {
        /* ... */
        providers: [
            provideMockStore( { initialState: fromReducer.initialState } )
        ]
    } ).compileComponents();
    store = TestBed.get<Store<State>>( Store );
  } ) );

  it( 'should load items in #ngOnInit', () => {
    store.setState( {
        item: {
          ...fromReducer.initialState,
          entities: { [item.id]: item },
        },
        otherFeature: null,
        otherFeature: null,
        otherFeature: null
    } );
    component.items$.subscribe( items =>
        store.select( ItemStoreSelectors.selectItems ).subscribe( fromStore => expect( items ).toEqual( fromStore ) )
    );
  } );
});

While everything is functioning correctly with using provideMockStore and setState, I find one particular aspect quite annoying:

store.setState( {
    item: {
      ...fromReducer.initialState,
      entities: { [item.id]: item },
    },
    otherFeature: null,
    otherFeature: null,
    otherFeature: null
} );

Each feature slice of the state needs to be added in the setState method. Otherwise, TypeScript will throw errors.


Instead of setting the entire root state, my preference would be to set only a specific feature slice like so:

store.setState( {
  ...fromReducer.initialState,
  entities: { [item.id]: item },
} );

However, I couldn't find any relevant documentation regarding using provideMockStore specifically for individual slices of state here.

Answer №1

It is advisable to consider a different approach in this situation. A more effective method would be to conduct unit tests on your selector and component separately.

NgRx 8 offers the option of using mock selectors. Utilize this feature in your component to confirm that the logic is functioning correctly.

Subsequently, perform individual unit tests on your selector to ensure it is operating as planned.

This approach ensures that the tests remain independent, resistant to fragility, and genuinely serve as unit tests.

Update: While the linked documentation is official, another method to mock your selectors is as follows:

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        provideMockStore({
          selectors: [
            {
              selector: yourSelectorNameHere,
              value: someMockValueHere
            }
          ]
        })
      ]
    });

Answer №2

Xander suggested utilizing mockSelectors to resolve the issue at hand. The TypeScript error is likely due to how you defined the types.

MockStore<State> may represent your entire state tree, but for a specific feature slice, consider using MockStore<FeatureState>

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

Observable emitting individual characters instead of the entire string in an optional parameter of an activated route

Within an Angular component, I have a method with the following content: this.route.paramMap.pipe( switchMap((params: ParamMap) => { let fooValue = params.get('selectedid'); console.log("inside switch map with value as " + ...

Having difficulty creating a TypeScript function

I've encountered a TypeScript error that has left me puzzled: src/helpers.ts:11:14 - error TS2322: There's an issue with this piece of code and I can't quite grasp it: Type '<T extends "horizontal" | "vertical" | undefined, U extends ...

A guide on obtaining the date format according to locale using Intl.DateTimeFormat within JavaScript

Can someone assist me in obtaining the standard date format (such as MM/DD/YYYY) based on a specified local id? The code snippet provided below is not returning the desired format. Any guidance on how to achieve this would be greatly appreciated. var da ...

Cookie authentication in CodeIgniter with Angular HTTP requests in Ionic 3

I am experiencing difficulties sending POST/get requests to the server. When using the Postman Chrome extension, everything works fine. However, when attempting to use Angular Http (not HttpClient) in Ionic, I encounter errors. The first error is related t ...

Ways to update the angular content following a switch in the current bootstrap tab?

My component displays multiple tabs, with only one active depending on the business logic. Here is a snippet of the code: <ul class="nav nav-tabs"> <li *ngIf="activateTab1" class="active"><a data-toggle="tab" href="#tab1"> < ...

Even as I create fresh references, my JavaScript array object continues to overwrite previous objects

Coming from a background in c# and c++, I am facing some confusion with a particular situation. Within the scope of my function, I am creating a new object before pushing it into an 'array'. Strangely, when I create the new object, it appears to ...

Sequelize: Query results do not have defined instance methods and properties

The Sequelize version is 6.6.2 Mysql2 version: 2.2.5 I have constructed my Model in the following manner and defined methods as shown: interface IUserAttributes { user_id: number; logon_name: string; user_password: string; full_name: string; di ...

Transferring information between components within AngularJS

export class AppComponent { title = 'shopping-cart'; ngOnInit() { } images = [ { title: 'At the beach', url: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?ixlib=rb-4.0.3&ixid=MnwxMjA ...

Creating a dynamic popup/modal in Angular 7 using a service

As a newcomer to Angular, I find myself with a question regarding services. In the past, when working with other languages, I would create self-contained components that could be called from anywhere within the application. Currently, my need for popup di ...

The functionality of the Bootstrap toggle checkbox is not functioning properly within the Bootstrap carousel

I'm encountering issues with bootstrap toggle checkboxes and editing checkboxes within a carousel. My requirement is to have a carousel with indicators. The carousel contains a table of workflows that need to be checked, as shown here: https://i.sst ...

Styling the `mat-hint` in Angular Material for large blocks of text

Currently, I am undertaking a project in Angular 9 and utilizing Material design. If you want to view a demo of my work, you can find it here: https://stackblitz.com/edit/mat-hint-styling-issue?file=src/app/app.component.html In my project, I am using in ...

Defining the data structure for the leaflet-search plugin in a React and Typescript environment

I have encountered an issue within my project involving the leaflet library. I am utilizing it to display maps containing images (such as floor plans of buildings), and each map includes a Point represented by a GeoJson Point denoting a specific sector on ...

S3 notification from CDK triggers cyclic reference issue

I am looking to set up an S3 bucket in one stack, pass it to another stack, and then utilize it for creating a notification in either an SNS or SQS. Below is an example of what the code breakdown would resemble. Stack 1 export class BucketStack extends Ba ...

What is the method for obtaining distinct hover-over values for individual items within a dropdown menu?

If utilizing angular2-multiselect-drop down, what is the correct method to obtain distinct hover over values for individual items in the drop down? When dealing with standard HTML, you can directly access each element of the drop down list if it's ha ...

HTML: Mark the chosen hyperlink or tag

In my HTML page, I am looking to keep the link selected when it is clicked on. Here is the initial HTML code: <table class="main-dev"> <tr> <td> <a class='titleForm' style="cursor:pointer"> ...

Encrypting sensitive information in JavaScript and Angular 2: SecureString

Is there a way to securely copy sensitive data to the clipboard in javascript/Angular2, ensuring that the string remains confidential by removing it from computer memory when no longer needed? In Microsoft .Net, there is a feature called System.Security.S ...

Angular's Mysterious Pipe

When navigating to the indice page, I want to adjust the number formatting in the cours column to display two decimal places. For instance: 11345.654589 should be displayed as 11345.65. https://i.stack.imgur.com/tjvWb.png To achieve this, I have created ...

The Extended Date type is indicating that the function cannot be located

I came across this helpful gist with date extensions: https://gist.github.com/weslleih/b6e7628416a052963349494747aed659 However, when attempting to use the functions, I encountered a runtime error stating: TypeError: x.isToday is not a function I foun ...

The autocomplete feature is now bypassing any text that comes after the #

return this.http.get(Configs.BASE_PATH + 'getTaxRates' + query + '&ts='+ Date.now()); query = "? The problem I'm encountering is related to my search query: 303 E 14 mile Rd, #305, Clawson, MI 48017. This ...

ESLint is indicating an error when attempting to import the screen from @testing-library/react

After importing the screen function from @testing-library/react, I encountered an ESLint error: ESLint: screen not found in '@testing-library/react'(import/named) // render is imported properly import { render, screen } from '@testing-lib ...