Evaluating observables in .pipe angular 8 jasmine

In my component, I have a subscription to triggerRuleExecutionService which is triggered by another component using next().

Within the pipe, I am using switchMap to make an HTTP service call and retrieve data from the database.

 this.ruleExecutionService = this.editCheckSVC.triggerRuleExecutionService.pipe(
      switchMap(res => {
        return this.editCheckSVC.executeRules(res);
      })
    ).subscribe(res => {
      console.log(res);
    });

This code snippet resides within the ngOnInit function.

Below is the test specification for the above functionality.

    const ruleExecutionSubject = new Subject();

    class EditChkManagementServiceStub {
      triggerRuleExecutionService = ruleExecutionSubject.asObservable();
      executeRules() {
        return of([])
      }
   }



describe('EditcheckManagmentComponent', () => {
      let component: EditcheckManagmentComponent;
      let fixture: ComponentFixture<EditcheckManagmentComponent>;
      let debugElement: DebugElement;
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [EditcheckManagmentComponent],
          schemas: [NO_ERRORS_SCHEMA],
          providers: [{ provide: EditCheckManagementService, useClass: EditChkManagementServiceStub }, HttpService],
          imports: [HttpClientModule]
        })
          .compileComponents();
      }));

      beforeEach(() => {

        fixture = TestBed.createComponent(EditcheckManagmentComponent);
        component = fixture.componentInstance;
        debugElement = fixture.debugElement;
        fixture.detectChanges();
      });


    it('should call rule execution API', () => {
        ruleExecutionSubject.next({
          formName: '',
          schedule: '',
          subSchedule: '',
          version: '',
          fiscalYear: '2018',
          accountingPeriod: '6'
        });

        fixture.detectChanges();
        fixture.whenStable().then(() => {
          const executionServiceInstance: EditCheckManagementService = TestBed.get(EditCheckManagementService);
          spyOn(executionServiceInstance, 'executeRules').and.callThrough();
          component.ngOnInit()
          expect(executionServiceInstance.executeRules).toHaveBeenCalled();
        });

      });
    });

The test case is failing with the message

Expected spy executeRules to have been called.

Can you identify what mistake may have been made here?

Answer №1

describe('EditcheckManagmentComponent Suite', () => {
      let component: EditcheckManagmentComponent;
      let fixture: ComponentFixture<EditcheckManagmentComponent>;
      let debugElement: DebugElement;
      let mockEditChkManagementService: any;

      beforeEach(async(() => {
        mockEditChkManagementService = jasmine.createSpyObj('editCheckSVC', ['executeRules']);
        
        // Initialize a BehaviorSubject for triggering rule execution service
        mockEditChkManagemenetService.triggerRuleExecutionService = new BehaviorSubject({
         formName: '',
         schedule: '',
         subSchedule: '',
         version: '',
         fiscalYear: '2018',
         accountingPeriod: '6'
        });
        
        TestBed.configureTestingModule({
          declarations: [EditcheckManagmentComponent],
          schemas: [NO_ERRORS_SCHEMA],
          providers: [{ provide: EditCheckManagementService, useValue: mockEditChkManagemenetService}],
          imports: [HttpClientTestingModule] 
        }).compileComponents();
      }));

      beforeEach(() => {
        fixture = TestBed.createComponent(EditcheckManagmentComponent);
        component = fixture.componentInstance;
        debugElement = fixture.debugElement;
        
        // Make mockEditChkManagementService return an empty array
        mockEditChkManagementService.executeRules.and.returnValue(of([]));
        
        // Trigger ngOnInit with fixture.detectChanges()
        fixture.detectChanges();
      });

    it('should invoke rule execution API', () => {
       expect(mockEditChkManagementService.executeRules).toHaveBeenCalledWith({
         formName: '',
         schedule: '',
         subSchedule: '',
         version: '',
         fiscalYear: '2018',
         accountingPeriod: '6'
        });
      });
    });

Consider expanding test coverage by utilizing more testing functionalities like describe, beforeEach, etc. For now, the current implementation seems fine.

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

Dealing with Angular 6 HTTP Interceptor and the frustrating net:: ERR_TIMED_OUT error

I have been puzzling over something recently that has left me scratching my head. Within my interceptor, there is code that deals with parsing and handling errors in specific ways based on factors such as status codes. While I haven't included this c ...

Implement a nested filter in Angular 8 to enhance data manipulation

Is it possible to apply a filter inside another filter in this scenario? I have a table of orders with nested tables of services, and I want to only display the orders where the type of service is 'type1'. I tried using the following line of code ...

Transforming JavaScript code with Liquid inline(s) in Shopify to make it less readable and harder to understand

Today, I discovered that reducing JavaScript in the js.liquid file can be quite challenging. I'm using gulp and typescript for my project: This is a function call from my main TypeScript file that includes inline liquid code: ajaxLoader("{{ &ap ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...

Presenting two arrays simultaneously creates angular duplicates

Encountering an issue while trying to display two arrays containing channel information: List of channels List of subscriptions that users have opted for. channels = [ { "id": 1, "name": "arte", "service&q ...

Do type declaration files for NPM packages have to be in the .d.ts format?

I believe it is feasible to include type declarations in any typescript file like '.d.ts', '.ts', or '.tsx'. However, I have observed that the type declaration files for most npm packages are .d.ts files. Is this a requireme ...

What is the best way to retrieve a soft deleted entity from typeorm in a postgreSQL database?

Can anyone help me figure out how to retrieve soft deleted documents from a PostgreSQL database using TypeORM's find, findOne, or query builder get/getMany methods? I keep getting undefined as the result. Is there a way to access these deleted values? ...

Tips for executing a code after a Firestore .update() operation is completed on the server side in Angular

When a user logs in, I want to send a locally generated token to be stored in both localstorage and firestore. The user is then routed to the admin component. In the app component, I will subscribe to the user and compare the stored token with the one in ...

Troubleshooting Angular 5: Interceptor Fails to Intercept Requests

I have a valid JWT token stored in local storage and an interceptor that I borrowed from a tutorial. However, the interceptor is not intercepting requests and adding headers as expected. Here's where I am making a request: https://github.com/Marred/ ...

Webpack focuses solely on serving HTML files, neglecting to deliver the underlying code

Hey there! I'm currently working on a project that involves using React, TypeScript, and Webpack. I ran into some errors previously that prevented the code from compiling, but now that's fixed. However, when I run webpack, it only serves the HTML ...

Having trouble getting undefined values for keys while attempting to retrieve all the data from Firebase DB with Angular

Currently, I have code that is fetching records from the Firebase database using both Angular and Ionic. The code functions properly, but it does not provide me with the keys for each record. Instead, it returns 'undefined'. I have researched s ...

Error: Unable to locate sportsRecord due to missing function

updated answer1: Greetings, I have updated the question with some detailed records and console logs for better understanding. sportsRecord = { playerTigers:[ {TigerNo: 237, TigerName: "Bird Bay Area", TigerkGroupNo: 1, isDefault: true ...

How to efficiently eliminate duplicates from a JSON array using Angular2

Struggling with filtering my JSON array in Angular2 after transitioning from Angular 1.x. It used to be so simple using 'unique' in the filter function to remove duplicates. Here is a snippet of the JSON data: {"app":"database_1", "host":"my_h ...

Tips on how to personalize the print layout of an Angular 4 page when pressing ctrl+p

I am working on an angular4 app and I encountered an issue when trying to customize the print page view by pressing ctrl+p in the browser. The page that needs to be printed contains only Angular components, and my attempts to modify the print view using ...

Adding Relative URLs Automatically to .angular-cli.json is a simple process that can be easily

Is there a way to automatically have Angular-Cli (Angular-4) append URL's to Styles or Scripts when adding external libraries with npm install --save into .angular-cli.json? Currently, we have to manually search through the node_modules folder to fin ...

Encountering Issues with Angular 2: Subject Not Functioning Properly in Http Get Request

Within my Angular application, I have a Form Page where employee data can be input and a Grid Page where entered data is displayed. The goal is for new data submitted through the form to automatically populate in the grid. Initially, I am loading existing ...

Transforming Post Requests into Options Requests

I am facing an issue with my Angular 6 API. After creating interceptors, my POST requests are turning into OPTIONS requests. What could be causing this problem? Here is the code for one of the Services: import { Injectable } from '@angular/core&apo ...

Angular 4 animations failing to run on Safari iOS 9.3

In my current app testing phase, I noticed that the angular animations are not functioning as expected in Safari iOS 9.3. Despite spending hours trying to troubleshoot the issue, I still couldn't resolve it on my own. Therefore, I am seeking assistanc ...

What exactly is the data type of setInterval in TypeScript?

If I want to define the type of a variable that will be used with setInterval in the following code snippet: this.autoSaveInterval = setInterval(function(){ if(this.car.id){ this.save(); } else{ this.create(); } ...

Is there a way to access all routes within Nestjs, including those from all modules and controllers?

Is there a way to retrieve a list of all available routes (controller methods) with their respective HTTP verbs using Nestjs? I would like it to be displayed in a similar format: API: POST /api/v1/user GET /api/v1/user PUT /api/v ...