Creating Test Cases for Service Response Validation

I am currently attempting to unit test an API within my ngOnInit method. The method is responsible for making a call to the service in order to fetch details. If the details are not undefined, an array called 'shoeDataResponse' of type *shoeData [] will be populated with these details and returned as the response.

*shoeDataResponse: shoeData[];

Below is the implementation of the method:

 ngOnInit(): void {
    this.shoeService.getShoeData().subscribe((shoeDetails) => {
      if (shoeDetails != undefined) {
        this.shoeDataResponse = shoeDetails;
      }
    });
  }

I am uncertain if this is the correct approach, but here is what I have attempted in the spec file:

  it('should return data if defined',  waitForAsync(() => { 
let shoeDataResponse = [
      {
        mCompanyIDEntity: {
          mbranchID: '108020',
          misShippingItem: true,
          mIsBranchNumber: false,
        },
        companyName: 'SOME COMPANY',
        shoeBalance: 1250.00,
        orderDate: '',
        mAccountHolder: false,
      },
    ];

    spyOn(ShoeService, 'getShoeData').and.returnValue(of(shoeDataResponse));
    component.ngOnInit();
    expect(component).toBeTruthy();
  }));

Upon running the test, I encounter an error stating, "Argument of type '"getShoeData"' is not assignable to parameter of type '"prototype"'."

Any assistance on resolving this issue would be highly appreciated. Thank you!!!

Answer №1

It appears that the issue lies in how you are setting up the spy for the getShoeData function. Rather than directly spying on the service class, you need to create a spy on the instance of the service that is injected into the component.

Start by creating an instance of the service:

  let shoeService: ShoeService; // initialize the instance

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ComponentName],
      providers: [ShoeService], // include the service in the providers
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(ComponentName);
    component = fixture.componentInstance;
    shoeService = TestBed.inject(ShoeService); // add this line to instantiate ShoeService
  });

Next, in your test, remember to spy on the shoeService instance rather than the ShoeService class method

spyOn(shoeService, 'getShoeData').and.returnValue(of(shoeDataResponse));

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

Utilizing Props in React to Slice and Dice Data Within a Separate Component

Currently, I am in the process of creating an about text for a profile that will include an option to expand or collapse based on its length. To achieve this, I am utilizing a function from the main home component: <AboutText text={aboutData}/> Abo ...

Is there a way to retrieve the default ObjectId generated by MongoDB when using NextAuth?

Is it possible to access the MongoDB ObjectId of the user currently logged in when using Next Auth with services like Twitter? When signing in, Next Auth creates a new user, account, and session, but I'm unable to retrieve the _id value for my server ...

Altering the appearance of an input field upon submission

https://jsfiddle.net/3vz45os8/7/ I'm working on a JSFiddle where I am trying to change the background color of input text based on whether the word is typed correctly or incorrectly. Currently, it's not functioning as expected and there are no e ...

I am facing an issue with updating the state dynamically within a useState object

Within my useState, there is an object containing a variety of values. I have an input field and am dynamically setting its value to useState[key], which works fine. However, the issue arises when I try to update these values. When I call onChange and use ...

ReactJS and Redux: setting input value using properties

I am utilizing a controlled text field to monitor value changes and enforce case sensitivity for the input. In order to achieve this, I need to access the value property of the component's state. The challenge arises when I try to update this field ...

Warning TS2352: There could be a potential mistake in converting a type 'Session | null' to type '{ x: string; y: string; }'

At first, I encountered the following errors: server.ts:30:12 - error TS2339: Property 'shop' does not exist on type 'Session | null'. 30 const {shop, accessToken} = ctx.session; ~~~~ server.ts:30:18 - error TS2339: ...

No changes made to Observable when it's empty

I encountered an unusual issue with the rxjs "filter" in my development environment: SAP ComposableStorefront / Spartacus "~2211.21.0" angular 17.2.0 Currently, I am on a product detail page and applying a filter to my Observable in the following manner: ...

Troubleshooting imagejpeg() Function Failure in PHP Server

I've been working on implementing image cropping functionality for my website. I've managed to send an array of cropped image dimensions (x, y, width, height) to my PHP script. On my localhost, the script successfully crops the image, but unfort ...

Error encountered in Angular10: XHR request for POST failed due to browser blocking HTTP Request to a domain with a similar name

I am encountering an issue with my webpage that consists of a Django REST API and an Angular 10 Frontend SPA. Normally, I can successfully send GET, POST, PUT, and DELETE XHR Requests to my backend without any problems. However, there is a specific API End ...

Accessing the "this" object in Vue.js components

When executing console.log(this) in the doSomething method, it returns "null". I was expecting console.log(this.currentPage) to display "main", but unfortunately, the "this" object is null.. :( Is there a way to access the value of "main" for currentPage ...

When attempting to trigger a function by clicking a button in Angular 8 using HTTP POST, nothing is happening as

I've been struggling to send a POST request to the server with form data using Observables, promises, and xmlhttprequest in the latest Angular with Ionic. It's driving me crazy because either I call the function right at the start and the POST wo ...

Exploring the concept of inheritance and nested views within AngularJS

I've encountered a challenge while setting up nested views in AngularJS. Utilizing the ui-router library has been beneficial, but I'm facing issues with separate controllers for each view without proper inheritance between them. This results in h ...

When logging off from an Angular2 application, the OIDC-client does not properly clear the cookies for the MVC application

I currently have an authorization server that is being used by both my Angular2 app and MVC webapp. In my Angular2 app, I've implemented authorization using the oidc-client JavaScript package. Everything works well except for the logout functionality ...

The modals equipped with data-dismiss="modal" and data-target="#id" do not navigate to their intended destination

Attempting to focus the input field using the modal data-target function on button click. The input field is focused, but a div called <div class="modal-backdrop in"> is created and the modal does not close properly. This prevents the user from click ...

Tips for distributing services in Angular

I'm currently working on an angular application that consists of different modules, with lazy loading enabled. In one of the modules, let's call it module A, I have a service called userService that I need to access in a component located in anot ...

Ways to extract variables from a component and utilize them in App.js

Despite my efforts to search online, I could not find the answer or understand what I needed to. My issue: I need the "inputVal" variable from the "InputField.js" component to be accessible in the "App.js" component (specifically in the fetch request where ...

Guide on invoking a Python function using vanilla JavaScript within a Django application

I'm currently developing a Django application and I'm attempting to invoke a Python function in views.py upon clicking a button. I'm aiming to achieve this using vanilla JavaScript, as my knowledge of JavaScript is limited and I prefer to ke ...

Implementing ControlValueAccessor in Angular 2 - A step-by-step guide

I'm encountering the error message "No value accessor for form control with unspecified name attribute" Some suggest adding ngDefaultControl, but it doesn't make any difference in my component When I try to use ControlValueAccessor instead, I s ...

unanticipated installation issue with published npm package on verdaccio

I am on a mission to create and release a package containing commonly used TypeScript functions on Verdaccio, an npm registry that operates on Docker. After completing the build for my TypeScript package, this is how my project structure looks: https://i ...

Transitioning an AngularJS factory to TypeScript

I'm currently in the process of transitioning an AngularJS application to Angular and one of the challenges I've encountered is converting my JavaScript code to TypeScript. While I've been successful with components and services, factories h ...