Performing Jasmine unit testing on a component that relies on data from a service, which itself retrieves data from another service within an Angular 2+ application

Attempting to implement unit testing for a service using httpmock has been challenging. The service in question utilizes a method to make http get calls, but I have encountered difficulties in writing the test cases.

saveservice.service.ts -- file

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
const envURL = sessionStorage.getItem('apiBaseURL');
 httpGet<T>(url) {
    const URL = envURL + url;
    return this.http.get<T>(URL, httpOptions);
  }

The saveservice.service file contains the httpGET() method, which is utilized by work.service.ts.

work.service.ts

import {SaveserviceService } from '../../.././my-service.service';

getworklist(employeeID){

    return this.saveservice.httpGet('work/v1/works?employeeid=' + employeeID);
  }

This demonstrates the connection between workservice and save service. Now, the challenge lies in writing unit test cases for work.component.ts file with the implementation of httpmock.

For reference, the apiUrl is defined in a separate file called env.ts -- env.ts

export const apivalue= {

    apiBaseUrl:"https://example.co/",
  };

work.component.ts

ngOnit(){
this.employeeID:this.id;
   this.workservice.getworkList(this.employeeID).subscribe(
      (data) => {
        this.workList = data;
       console.log(" ggghfghfgh", this.worklist);
      }, (error) => {
        console.log(error);}

The above code snippet showcases work.component.ts file for which unit test cases need to be written. Assistance is required to accomplish this task.

work.component.spec.ts

 let httpMock: HttpTestingController;
 let injector: Injector;
  let workservice: WorksService;
let saveservice123: SaveService;

 providers: [
        Injector,
        HttpClient,
        HttpClientTestingModule,
        saveService,
        worksService
      ],

  httpMock = TestBed.get(HttpTestingController);
    workservice = TestBed.get(WorksService);
    saveservice123 = TestBed.get(SaveService)

  fit('getting work detsails indivually', async(() => {

    fixture = TestBed.createComponent(worksComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    workservice.getworkList(123).subscribe(() =>{});

    const request = httpMock.expectOne("work/v1/works?employeeid=")
    // expect(request.request.method).toBe('httpGet');
    // request.flush(xxxxx);

An error is being thrown:

Error: Expected one matching request for criteria "Match URL: work/v1/works?employeeGuid=", found none.

Assistance is needed on how to properly write unit test cases for this scenario. Attempts using spy have also proven unsuccessful.

const mockdata = { id:1, title: "Hello world",  paste: "console.log('Hello world');"}
     const spyOnAdd = spyOn(service, "getworkList").and.returnValue(mockdata);

Answer β„–1

Start by ensuring that your component includes the OnInit interface and that its ngOnint method is changed to ngOnInit.

When testing your component, focus on its behavior rather than the implementation of WorkService. This means mocking relevant parts of the WorkService for unit testing.

If the only parameter passed to the constructor of WorkService is SaveService, a basic example of work.component.spec.ts could be as follows:

import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
...

describe('WorkService', () => {

    const workList = [...]; // specify result of WorkService#getworklist
    const workService = new WorkService(null);
    let fixture: ComponentFixture<WorkComponent>;

    beforeEach(fakeAsync(() => {
        spyOn(workService , 'getworklist').and.returnValue(Promise.resolve(workList));
        TestBed.configureTestingModule({
            imports: [...],
            declarations: [WorkComponent],
            providers: [
                { provide: WorkService, useValue: workService }
            ]
        });
        fixture = TestBed.createComponent(WorkComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        tick();
    }));

    it('getting work details individually', () => {
        expect(workService.getworklist).toHaveBeenCalled();
        expect(component.workList).toEqual(workList);
    });
});

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

Optimizing Your Angular2 Bundle with Webpack: Best Practices for Minimizing Code Size

I have attempted to include the --optimize-minimize option in my webpack command (version 2.1.0-beta.27), but I am still receiving a bundle.js instead of a bundle.min.js: "build:production": "node_modules/.bin/del-cli public/js/app && node_module ...

Can you explain the concept of server-side rendering with Angular 2?

I've heard that angular2 is utilized for server-side rendering, and I'm curious to learn more about it. Here are some questions I have regarding this concept: 1. What exactly is server-side rendering? 2. What issues does it address? 3. What a ...

6 Ionic date-time selector

I seem to be encountering some challenges while using Ionic 6 with the new date-time picker. The issue arises when I retrieve a value from the database through a nest service. In the database, the date appears as: β€œ2022-06-30 13:11:54” but upon retriev ...

A guide on iterating through a JSON object in Vue and Javascript to retrieve keys and values, checking if they are either distinct or null

Looking for a way to iterate through a JSON object that may or may not have properties fields, which can be null or contain various configurations. I need to display it in a code block. Below is the example JSON data: "grade": [ { ...

Ensuring that all checkboxes have been selected

I have 5 checkboxes all with the attribute name set as relative-view. To confirm that all of them are checked, I know how to verify the first and last one: expect(element.find('input[name="relative-view"]').first().prop("checked")).toBe(true); ...

Having trouble accessing JSON response properties within an Angular.js controller

My Angular.js controller is called 'forecastController'. This is the code for the Angular.js Controller: weatherApp.controller('forecastController', ['$scope','$routeParams','cityService', 'weat ...

Attempting to use express and nodemailer to send an email, but there is absolutely no output appearing in either the console or the terminal

When I click the send email button, it should send the data to a mailhog inbox. However, nothing happens - no errors in the console or terminal. My goal is to use nodemailer to send the name, email, chosen plan, and message from the form to the mailhog add ...

React: Selecting Component Name Based on Provided Property

My goal is to dynamically load an icon component in React passed as a prop from the parent component. Dashboard (parent): import { Button } from './components'; function App() { return ( <div className="app"> <d ...

The function given to requestAnimationFrame is not being triggered as expected

I have successfully implemented an infinite loop animation using setInterval. However, I want to enhance the performance by switching to requestAnimationFrame(). Unfortunately, the function supplied to requestAnimationFrame() is not being called for some r ...

Filling a martial arts training center's drop-down menu with choices using an Ajax response message

Within my application, there are two drop down menus. The first drop down menu allows users to select the type of institution, and I have added an onchange event that triggers a JavaScript function to make an AJAX call in order to populate the second drop ...

Why is the autocomplete minlength and maxheight not functioning properly in MVC?

After entering a value in the text field, data from the database appears but adjusting the height and width of the list box seems to be a challenge. I have set the parameters like minLength: 0, maxItem: 5, but it doesn't seem to make a difference. ...

An easy way to adjust the date format when linking a date in ng-model with md-datepicker

<md-input-container> <label>Scheduled Date</label> <md-datepicker ng-model="editVersionCtrl.selectedPlannedDate" ng-change="editVersionCtrl.checkPlannedDate()"> </md-datepicker> </md-input-container> ...

Is it possible to utilize setTimeout to demonstrate the execution of a while loop visually?

I am working on a function that generates random numbers between 1 and 6 until it matches a target value of 3. I want to create a visual effect where each randomly generated number is displayed on the page, but I'm facing some challenges with delays. ...

Save the JSON data into a variable inside a React utility component

Currently, I am new to React and facing an issue with fetching data and storing it in a variable. I have been struggling to understand why my SetMovieResponse function is not working as expected. I have tried stringifying the JSON before sending it, but w ...

Troubleshooting: Issue with jQuery not retrieving the value of input:nth-child(n)

My goal is to dynamically change the price when the model number changes, requiring the id number and quantity to calculate it accurately. Here is the HTML code I have: <div class="col-sm-9 topnav"> <span> ...

Watch mp4 clips in various languages with ExpressJs

I have a question regarding streaming videos within my local network. My mp4 files contain multiple audio tracks in different languages. Is there a way to select a specific audio track to stream? For instance, could you specify a language as a query parame ...

Leveraging npm for the development of my TypeScript/Node.js project

I'm facing challenges working on a project written in TypeScript and running on Node. I am finding it difficult to write the npm script to get it up and running properly for development purposes. What I am attempting to achieve is: clear the /dist f ...

Is it possible to write a text file in UTF-16 using Javascript?

I need to create a UTF-16 text file from a string. For instance: var s = "aosjdfkzlzkdoaslckjznx"; var file = "data:text/plain;base64," + btoa(s); The above code generates a UTF-8 encoding text file. How can I modify it to produce a UTF-16 text file usin ...

Tips for removing an element from an array in a JSON structure using its unique identifier

This problem seems to be fairly straightforward but it’s giving me some trouble. Here is the JSON structure I'm working with: "playlists" : [ { "id" : "1", "owner_id" : "2", ...

Using TypeScript with Angular-UI Modals

Currently, my goal is to create a modal using angular-ui-bootstrap combined with typescript. To begin, I referenced an example from this link (which originally utilizes jQuery) and proceeded to convert the jQuery code into typescript classes. After succes ...