Simulating MatSnackBar in Angular 8 using Jasmine Testing

My Angular 8 application utilizes the Angular Material MatSnackBar, and I am currently in the process of testing whether the open() method of this class is triggered. The invocation of open() happens within an NgRx store selector as shown below:

ngOnInit() {
  this.store.dispatch(fromStore.getFeaturedPlaylists());

  this.subscription = this.store.pipe(
    select(fromStore.selectError),
    filter(err => !!err),
    switchMap((err) => this.snackBar.open(
      `Error: ${err.message}`,
      'Try again',
      {duration: 5000}).afterDismissed())
  ).subscribe(() => this.store.dispatch(fromStore.getFeaturedPlaylists()));
}

The segment of my test related to this scenario is presented here:

describe('FeaturedPlaylistsComponent', () => {

  let component: FeaturedPlaylistsComponent;
  let fixture: ComponentFixture<FeaturedPlaylistsComponent>;
  let matSnackBarSpy: jasmine.SpyObj<MatSnackBar>;

  beforeEach(async(() => {
    const spy = jasmine.createSpyObj('MatSnackBar', ['open']);

    TestBed.configureTestingModule({
      declarations: [
        // other declarations here
        FeaturedPlaylistsComponent
      ],
      providers: [
        // other providers here
        {provide: MatSnackBar, useValue: spy}
      ]
    })
    .compileComponents();

    matSnackBarSpy = TestBed.get<MatSnackBar>(MatSnackBar);
  }));

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

  describe('#ngOnInit()', () => { // fails
    // lots of other test...
    it('should call MatSnackBar.open() on error', () => {
      const error = new HttpErrorResponse({error: 'Some error'});

      component.ngOnInit();
      store.dispatch(fromStore.setError({error}));

      expect(matSnackBarSpy.open).toHaveBeenCalled();
    });
  });

});

I was somewhat surprised by the success of the test confirming the functionality of the ngOnInit() function, especially given that no tick(5000) delay was included to account for dialog dismissal.

Moving the open() call to the beginning of the function resulted in a working

should call MatSnackBar.open() on error
test. This leads me to believe that the issue lies with the placement of the open() call inside the store selector block.

If anyone can shed light on why the

should dispatch a getFeaturedPlaylists() action on error
test succeeds while the
should call MatSnackBar.open() on error
test fails, I would greatly appreciate the insights.

Answer №1

Upon further investigation, I discovered that the issue stemmed from using a mock store instead of the actual store, resulting in none of the selectors functioning correctly. After switching to the authentic store and making some adjustments, I was able to successfully get them to work as intended.

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

What could be causing the app.component.html expression to be invoked repeatedly in my application?

As I was analyzing the evaluation of an expression in the main template app.component.html, I noticed that the trace appears exactly 5 times every time I refresh the page or click on any link. Curiously, when I placed a trace in the ngOnInit of app.compone ...

Using Typescript to set a custom timeout duration based on a dynamic variable within a for loop

My function includes a timeout that changes every 3 seconds: setActiveImage(promotions) { for (let i = 0; i <= promotions.length - 1; i++) { setTimeout(()=> { this.activeImage = 'http://myrul/public/Commercials/' + promo ...

Encountering difficulty adjusting the size of my charts when attempting to utilize the billboard.js chart library with Angular 6

I am currently working on integrating the billboard.js chart library with Angular 6, but I am encountering an issue with the size of the chart. Upon the initial page load, the chart appears larger than its containing div element. However, when I resize the ...

Encountering an issue when attempting to convert data to JSON in Angular 13, as the content type 'text/plain;charset=UTF-8' is not supported. This problem arises after sending data from

I've been attempting to submit a form using the following method: saveBuildcompany(): void { // @ts-ignore // @ts-ignore console.log(this.group?.value); let data2=this.group.value; let serializedForm = JSON.stringify(data2) ...

Is it possible to utilize ngIf to reuse a component when encountering a 404 error? How can the error be captured?

In my app-routin.module.ts file, I have a root component named HomeComponent that I reuse for unknown routes. const routes: Routes = [ { path: '', component: PrimaryComponent, data: { breadcrumb: 'PRIMARY'}, children: [ { p ...

Retrieve an array of object values using Angular and TypeScript

I'm attempting to extract the values of objects in an array using a nested for loop. I am receiving JSON data as shown below and have written the following TypeScript code to achieve this. However, I am unable to successfully bind the values to the te ...

The HTTP post method is not consistently triggering

Currently, I am in the process of developing a logout feature for angular (with a spring backend). The logout action is triggered by sending an HTTP post request to /auth/logout, where the endpoint invalidates the auth-token and refresh-token HTTP-only coo ...

Progressively cycle through each group within an array of reactive forms

My goal is to display array data in a reactive format and iterate over a group within the array based on my data. Here is an example of how my data structure looks: { nombre: 'Inca Suprema' precios: [ { precio: 16, variante: & ...

When a class decorator is returned as a higher-order function, it is unable to access static values

Check out this showcase: function Decorator(SampleClass: Sample) { console.log('Inside the decorator function'); return function (args) { console.log('Inside the high order function of the decorator: ', args); let sample = ...

A guide to positioning the content of an Angular tag within a span element

Can someone help me figure out how to properly align the PO number and Vendor information on my page? from PO Number: 344 Vendor: yu PO Number: 3445 Vendor: yu PO Number: 344 Vendor: yu to PO Number: 344 Vendor: yu PO Number: 3445 Vendor: yu PO Num ...

Display the Angular Material sidebar within the parent component's closing tag

I am using an angular material sidenav, but every time I open it, the sidenav is always positioned at the left side of the window https://i.sstatic.net/80VQ0.png However, I want the sidenav to always open at the end of the component with a blue backgroun ...

Accessing the property of an object with TypeScript

I am working with an array of objects, where each object contains two properties: {key:count} When configuring my chart, I need to set the data source in this format: {meta: "unknown", value: [the count of unknown]}, {meta: "male", value: [the count of ...

Pairing objects by utilizing a Universal Mapper

Classes Defined: abstract class ModelBase { id: string; } class Person extends ModelBase { favoriteDog: Dog | undefined; favoriteDogId: string | undefined; dogs: Dog[] } class Dog extends ModelBase { id: string; ownerId: string; name: strin ...

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

Guide to setting a dynamic value for an input List property in Angular

How can I render multiple dropdowns in Angular based on the response from an API? Currently, when I retrieve data from the API, I am seeing the same information displayed in both dropdown controls. Is there a way to assign dynamic values to the "list" prop ...

The list in Ionic 3 search does not appear after clearing the search bar

Can anyone assist me with my search bar issue? I'm able to display words on the list, but once I clear the search bar, nothing shows up. Here is a snippet of my code: In my home.html file: <ion-searchbar (ionInput)="getItems($event)" [showCancelB ...

Guide to dynamically including a tooltip in an input box using Angular 2

I need to implement a feature where a Tooltip message is displayed when hovering over an input box. The content of the Tooltip message will depend on the response received from a service. If the service responds with 'true', the Tooltip message s ...

Using Typescript: Including an additional argument

While experimenting with the code provided in the documentation interface Point { x: number; y: number; } function getX(p: Point) { return p.x; } class CPoint { x: number; y: number; constructor(x: number, y: num ...

What could be causing the error message "Unable to access 'http' property of undefined" to appear in this validator?

Can someone help me with creating an asynchronous validator for a reactive form control that checks if a username already exists? Below is the code for the async validator: userdata.service.ts import { HttpClient } from '@angular/common/http'; i ...

Find strings that contain some text other than Angular expressions using Regex

I recently discovered a need to identify strings in our projects that are not AngularJS expressions due to expanding into multiple languages. This includes any string that is not completely enclosed in curly braces. My goal is to create a regex pattern th ...