Tips for conducting tests on ngrx/effects using Jasmine and Karma with Angular 5 and ngrx 5

Here is the file that I need to test. My current focus is on some effects service while working with Angular5 (^5.2.0) and ngrx5 (^5.2.0). I have been struggling to properly implement the code below for testing purposes. Any tips or suggestions would be greatly appreciated. Thank you!

import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';
import { FETCH_DATA } from '../reducers/data.reducer';
import { DataService } from './data.service';
import { Subject } from 'rxjs/Subject';
import { ActionWithPayload } from '../types/app-actions';

@Injectable()
export class AutoCompleteEffects {
  public autoComplete$ = new Subject<{
    type: string;
    payload: { results: string[]; searchValue: string };
  }>();

  @Effect()
  getData$ = this.actions$.ofType(FETCH_DATA).switchMap((action: ActionWithPayload) => {
    return this.data
      .getData(action.payload)
      .map(results => ({
    type: 'FETCHED_DATA',
    payload: { results, searchValue: action.payload }
      }))
      .catch(() =>
    Observable.of({
      type: 'FETCHED_DATA',
      payload: { results: [], searchValue: action.payload }
    })
      );
  });


  constructor(
    private actions$: Actions,
    private data: DataService,
  ) {
    this.getData$.subscribe(action => this.autoComplete$.next(action));
  }

  public getAutoCompleteEffects() {
    return this.autoComplete$.asObservable();
  }
}

Answer №1

If you want to set up ngrx effects testing, there are a few key elements to consider:

  1. Follow the recommended approach of using provideMockActions for testing (see this guide)
  2. Mock the DataService and inject it into your tests

Once these steps are completed, you can proceed with testing different actions using the following example:

it('should suggest auto complete values', () => {
  actions = of([<test-actions>]);
  const expectedEffects = of([<expected-actions-from-effects>]);

  expect(TestBed.get(AutoCompleteEffects).getData$).toBeObservable(expectedEffects);
});

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

Discrepancy detected in AGM Map printout

When attempting to print my Angular AGM Map from Chrome, I noticed a large grey gap in the map. This gap is visible even when "background graphics" are turned off and it causes the map image below it to shift downwards. If you want to reproduce this issue ...

"In Nextjs, it is not possible to utilize the alert function or assign variables directly to the window object

Are you attempting to quickly sanity test your application using the window object's alert function, only to encounter errors like "Error: alert is not defined"? import Image from "next/image"; alert('bruh'); export default function Home() ...

Guidelines for redirecting to a complete URL

I am currently developing a web application using Angular 7. One of the features I need to implement is redirecting to a full URL that is retrieved from a database. The challenge here is to perform the redirect within the app without causing a full page re ...

Adjusting the alignment of button text in an Angular Kendo grid

I am currently utilizing the grid view feature of Kendo UI for Angular. While I have buttons on the grid, the issue is that the text within the buttons is not centered properly despite applying styles such as text-align:center. Here is the template for my ...

Step-by-step guide on developing an AngularJs provider using TypeScript

As I've developed a Directive that incorporates various Css classes, it would greatly enhance its flexibility if the Css classes could be configured at Application start within the config section. I believe utilizing a provider is the appropriate appr ...

Issue with locating module 'swiper_angular' during Jest unit testing following upgrade from Swiper 6 to 7

Encountering an issue with my unit tests post upgrading from Swiper 6 to 7. My setup includes Angular 12 and Swiper 7.3.1. The unit tests were functioning properly before the upgrade (Swiper version 6.5.9). Incorporating the SwiperModule in my tests like ...

Guide on linking enum values with types in TypeScript

My enum type is structured as follows: export enum API_TYPE { INDEX = "index_api", CREATE = "create_api", SHOW = "show_api", UPDATE = "update_api", DELETE = "destroy_api" }; Presently, I have a f ...

Having trouble loading static files in Django Angular framework? Specifically, images stored in the assets folder returning a

In my Angular project, I have an assets/image folder within the src directory where all my images are stored. Various components and child components in my app use these images like <img src"../../../assets/image/test.png">. After building my Angula ...

Ways to receive a reply from EventEmitter

From the child component, I made a call to a certain method. Here is the code in the child component: @Output() parentEvent = new EventEmitter<any>(); click1() { //calling the specified method from the child this.parentEvent.emit(myObj1); ...

Sorting complex strings in Typescript based on the dates contained within them

How can I sort a list of 2 strings with dates inside them so that the earlier one always comes first? The date is always after the second comma. For example, const example = ["AAA,5,2020-09-17T21:14:09.0545516Z", "AAA,0,2020-09-03T20:38:08. ...

What is the best way to turn off template binding for a specific section of a template in Angular2?

Can someone help me figure out how to show the {{ name }} string in an Angular 2 template? Is there a way to turn off template binding for only a section of the template? Thanks in advance! ...

How can I assign a type to an array object by utilizing both the 'Pick' and '&' keywords simultaneously in TypeScript?

As a beginner in TypeScript, I am looking to declare a type for an array object similar to the example below. const temp = [{ id: 0, // number follower_id: 0, // number followee_id: 0, // number created_at: '', // string delete_at: &ap ...

Angular - Issue with setting default value in a reusable FormGroup select component

My Angular reusable select component allows for the input of formControlName. This input is then used to render the select component, and the options are passed as child components and rendered inside <ng-content>. select.component.ts import {Compon ...

Tips on injecting configuration into forRoot

Is there a method to inject configuration object into AppModule's forRoot() function? How can I access the configService if there is no constructor within the module? config.yml: smtp: host: 'smtp.host.com' port: 10 secure: true aut ...

Retrieving latitude and longitude from place id in an Angular Google Maps component

Currently utilizing the google-maps component to extract latitude and longitude from Google Maps prediction data. Additionally, I have integrated a search bar using google-maps component. I have successfully implemented a search bar with ngx-google-places ...

What is the best way to iterate through the result of an HTTP request in Angular 11?

I am a beginner with Angular and currently working in Angular 11. I am facing issues with making an http request. Despite going through numerous Stack Overflow posts, none of the solutions seem to work for me, even though some questions are similar to mine ...

Implementing a database-driven user value in an Angular Material dropdown

My code successfully populates input fields in a reactive form, but I'm facing an issue with the dropdown field not getting populated. user.component.ts: onSelect(user: User): void { this.draw.toggle(); this.userForm.reset({ displayNam ...

After encountering an error, the puppeteer promptly shuts down the page

During my page testing, an error is thrown by a dependency. Although the error is not critical and does not impact my application, when testing with Puppeteer and encountering this error, it abruptly closes the tested page. How can I bypass this error to c ...

There seems to be an issue with running a PHP script in Angular when using a Proxy server

I have been attempting to retrieve data from a separate localhost server while both it and the "Angular localhost" are running simultaneously. Here is the code I am using: const req = new HttpRequest('GET', 'http://localhost:4200/echo.php&a ...

What is the process of converting an Array that is nested within an Object?

I am facing compile errors while attempting to convert an Object containing an Array of Objects. Here is the initial structure: export interface CourseRaw { metaInfo: MetaInfoRaw; gameCode: number; gameText: string; images?: ImageRaw[]; // Having ...