Sinon fails to mock the provided URL when GET request includes parameters

I am currently working on creating test cases for the services in my Angular application and encountering some challenges.

Below is the code snippet for the service:

/**
 * Sends http request to fetch client states and territories available for a specific vertical
 *
 * @param {number} vertical id of the specific vertical. Mapping:
 *    0 - Federal
 *    1 - State
 *    2 - Local
 *    3 - Education
 * @returns {Observable<State[]>} an array of state objects with display name and value as observable
 */
getClientsStatesByVertical(vertical: VerticalEnum): Observable<State[]> {
  let params = new HttpParams();
  if (vertical != null) {
    params = params.append('vertical', String(vertical));
  }
  return this.http
    .get(`${CLIENT_API_ENDPOINT}/csr/states`, {params: params}) as   Observable<State[]>;
}

And here is the test I have written:

it('#getClientsStatesByVertical with specified vertical', (done) => {
  const expectedResponse = [{label: 'Georgia', value: 'GA'}];
  server.respondWith('GET', `${CLIENT_API_ENDPOINT}/csr/states?vertical=${VerticalEnum.Federal}`);
  const observable = service.getClientsStatesByVertical(VerticalEnum.Federal);
  observable.subscribe(response => {
    expect(response).toEqual(expectedResponse);
    done();
  });
  server.respond();
});

Upon running this test using Karma, I encountered the following error:

HttpErrorResponse: Fake server request processing threw exception: Http failure response for http://localhost:19000/api/v1/clients/csr/states: 404 Not Found

I would appreciate your assistance in identifying the issue as it seems like a simple oversight, especially since similar cases with shorter URLs are functioning correctly.

Answer №1

Oops, I totally spaced on including the response in the respondWith function :)

server.respondWith('GET', `${CLIENT_API_ENDPOINT}/csr/states?vertical=${VerticalEnum.Federal}`, JSON.stringify(expectation));

But hey, problem solved!

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

Update the registerForm input from a boolean value to a number

Confused about how to convert a boolean to a number Issue : I'm struggling trying to convert my registerForm.value.aleas, which is a checkbox, into a number (0 for false, 1 for true) in order to perform a POST request (the API expects values of eith ...

Retrieving values from an array in a JSON response using Angular 4

How can I access the SubjectCode field in an array at a table using Angular 4? When trying to do so, I receive the error message: "[Error trying to diff '[object Object]'. Only arrays and iterables are allowed]". Here is the Json Response: { ...

Initiating a post request to the express server

My service includes a function that retrieves the user's current location using latitude and longitude coordinates. I am attempting to send this information to my server in order to incorporate it into a query. However, my post request does not appear ...

Crafting a dynamic HTML template in Angular using template literals and the *ngFor directive

I've been developing a toast component that accepts HTML tags as strings. This requires me to iterate through the errorMsgs array below and dynamically build a list. However, I'm currently facing an issue where the *ngFor loop inside it is iterat ...

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 ...

Why is TypeScript resorting to using 'any' for specific prop type definitions in React?

Having some trouble with my props typing: export interface ITouchable { isDisabled?: boolean; margin?: Margin; height?: number; bgColor?: string; } The definition of Margin is as follows: type Margin = | { top?: number; bottom?: nu ...

Is it possible to verify type equality in Typescript?

If the types do not match, I want to receive an error. Here is an example of an object: const ACTIVITY_ATTRIBUTES = { onsite: { id: "applied", .... }, online: { id: "applied_online", .... }, ... } as co ...

Communicate between sibling components in Angular by passing the selector of one component to another

Within my project, I have two sibling components located in the SecondComponent folder. The SecondComponent consists of both the main component and its child component. Now, in the FirstComponent, I need to access the child component of the SecondComponent ...

Code for Stripe Connect processed through AWS Amplify's authentication system

Within the structure of my Angular application, I have successfully integrated AWS Amplify with OAuth and Hosted UI, resulting in a seamless connection process. Specifically, when attempting to link with Google, I am directed back to an URL similar to http ...

Angular HTTP client fails to communicate with Spring controller

Encountered a peculiar issue in my Angular application where the HttpClient fails to communicate effectively with the Spring Controller. Despite configuring proper endpoints and methods in the Spring Controller, the Angular service using HttpClient doesn&a ...

`End Angular2 session and close browser tab`

Currently, I am developing a web application using Angular2. I am looking to include a button in the application that, when clicked, will not only close the application but also the browser tab where it was launched. I have been exploring various solution ...

I need assistance with adding a button to a table cell that triggers an action when clicked

I need to add a button to the table cell when I click a button to insert a new row in an Angular table. Although I am successful in adding a new row, I am facing difficulty in including a button in the cell along with the newly created row. ...

Error: Attempting to access the value property of a null object within a React Form is not possible

I am currently developing a form that includes an HTML input field allowing only numbers or letters to be entered. The abbreviated version of my state interface is outlined below: interface State { location: string; startDate: Date; } To initiali ...

Different Option for Nginx Server

Currently I am utilizing an AWS EC2 instance to host both my NodeJs backend and Angular frontend. Additionally, I am leveraging Route 53 for routing purposes and purchased a domain from GoDaddy. The hosting process involved the following steps: For the b ...

Error in Subscribing to Angular 8 Async Pipe

Check out this Full StackBlitz example: https://stackblitz.com/edit/angular8-async-pipe The app component template contains three identical components: <app-loader></app-loader> <app-progress></app-progress> <app-spinner>< ...

Difficulty encountered while managing dropdown functionality in Protractor using TypeScript

I'm encountering some difficulties when it comes to selecting a dropdown in Protractor. Here's the structure of my DOM: https://i.stack.imgur.com/qK8sT.png This is the XPath I'm using to select the dropdown with the value "Yes": //label[ ...

Tips for formatting nested Angular components in a visually pleasing manner:

Seeking guidance on the best approach for the following scenario: I have an angular component positioned at a specific route. Let's say the route is: /main-page Currently, the template spans the full width of the screen at this route. I want to add ...

Unleashing the Power of RxJS with OR Conditions

I am working with two Observables. For instance, I am waiting for either an HTTP POST call or a WebSocket call to return so that I can proceed. Once either call returns, I need to verify the information until a certain condition is met. In the following e ...

Unexpected termination during the npm installation process without providing a clear error message

Every time I try to create a new Angular2 app using the command ng new new-app, angular-cli successfully generates the necessary files and then proceeds to run npm install. However, the npm install process abruptly stops with no error message provided. As ...

Is there an alternative method to invoke the function aside from setTimeOut()?

if(i==1){ this.resetScreens(); this.editJobScreen1 = true; if(this.selectedLocations.length > 0){ this.locationService.getLocationByInput({ maxResultCount:16, skipCount: 0 }).subscribe((ele)=>{ ...