There was an issue encountered when attempting to subscribe via the Angular HTTP request

Currently I am working on an Angular app that is test driven, which is a requirement specified by the client.

I have been given a spec that cannot be altered or edited.

  it('should get results', fakeAsync(
    inject(
      [XHRBackend, NewsService ],
      (mockBackend: MockBackend, newsService: NewsService) => {

      const expectedUrl = 'https://api.nytimes.com/svc/topstories/v2/home.json?api-key=315a5a51483b469a918246dc2753b339';

      mockBackend.connections.subscribe((connection : MockConnection) => {
          expect(connection.request.method).toBe(RequestMethod.Get);
          expect(connection.request.url).toBe(expectedUrl);

          connection.mockRespond(new Response(
            new ResponseOptions({ body: mockResponse })
          ));
        });

      newsService.getSectionNews('home')
        .subscribe( (res: any) => {
            expect(res).toEqual(mockResponse);
        });
    })
  ));

Based on this spec, I need to develop my front end code.

This is what I have coded so far:

  import { Http } from '@angular/http';

  constructor(private http: Http) {}

  getSectionNews(sectionName: string): any {
    // fetch news of that sectionName
   // return this.mockResponse;
   const expectedUrl = 'https://api.nytimes.com/svc/topstories/v2/home.json?api-key=315a5a51483b469a918246dc2753b339';
   return this.http.get(expectedUrl).subscribe(res => res);
  }

However, when running the test case, I encountered the following error:

TypeError: newsService.getSectionNews(...).subscribe is not a function

Please shed some light on where I might be going wrong here.

I aim to pass the test successfully.

UPDATE

After updating my service's spec.

  getSectionNews(sectionName: string): Observable<any> {
    const expectedUrl = `https://api.nytimes.com/svc/topstories/v2/${sectionName}.json?api-key=315a5a51483b469a918246dc2753b339`;
    return this.http.get(expectedUrl);
  }

Now I encounter the following error:

Expected Response with status: null null for URL: null to equal Objectt({ status: 'OK', copyright: 'C ...

Answer №1

retrieveNewsBySection(sectionName: string): Observable { // retrieve news related to the specified section this.apiURL =

https://api.nytimes.com/svc/topstories/v2/${sectionName}.json?api-key=XXXXXXXXXXXXXXXXXXXXXXXXX
; return this.http.get(this.apiURL).map((res) => res.json()); }

The code provided above will address the mentioned problem. Appreciate it!

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 is the best way to limit the number of items displayed in a Bootstrap card?

While using bootstrap cards to display content, I encountered an issue when integrating it with the backend for looping. The items were continuously added to the right side instead of being set in columns of 3 and continuing straight down. It should look ...

The css property of *ngContainerOutlet is ineffective when applied to an ng-component with encapsulation

When I utilize *ngContainerOutlet to dynamically insert components, it wraps the component's template within an ng-component tag which causes my CSS styles to become ineffective. For example: <div class="my-class"> <ng-container *ngComp ...

Vercel encountered issues with "validating code quality and type correctness" during deployment but was successful when performed locally

Running "next build" locally and "vercel build" both work smoothly. However, once deployed to vercel, the "Linting and checking validity of types" fails during the build process. It seems like TypeScript is stricter when building on vercel even with the sa ...

Changing from localhost:3000/admin to localhost:3000 within the local server

I am currently developing a node.js application. My goal is to have the homepage rendered after the admin successfully uploads data, transitioning from localhost:3000/admin to localhost:3000. I attempted to achieve this using the code snippet below: route ...

What is the reason behind CORS errors being triggered by the inclusion of an HTTP Interceptor?

I am currently building an Angular 6 application that communicates with a PHP REST Api. I am running my development environment on localhost, and in order to avoid CORS errors, I had to enable the Access-Control-Allow-Origin: * setting. Lately, I have bee ...

The issue of button onclick textfield validation malfunctioning

Within this container, there is a text field identified as 'codeCityId' along with a button that triggers an onclick method. When the button is clicked, the function will verify the input. function click()={ var valid = $('#codeCityId' ...

Firebase line. Personalized completion status

Looking for guidance on launching different specifications based on incoming data. Struggling to declare multiple "finished states" in my spec and seeking advice on alternative methods. Can anyone assist me with this? Thank you! checkRelationship.getReq ...

Laravel validation successfully validates Vanilla AJAX request, but the controller does not receive the values

Currently, I am utilizing AJAX (vanilla JS) to send a form to a Laravel 5.5 controller for searching the Amazon products API. The AJAX is sending the correct keywords and category inputs, but the controller is not receiving them. Even though the request p ...

Does the phrase "assigning a closure to a variable" make sense within the realm of JavaScript?

I'm eager to understand the explanation for line 20 in my code example. Line 9 declares a variable named func1. It's set to the closure returned by invoking the function foo(). I understand that calling the function foo() not only returns the ...

What is it about Typescript's "typeof function" that meets the Generic Condition of "extends (...args: any[]) => any"?

Consider the code snippet below: type Params<F extends (...args: any[]) => any> = F extends ((...args: infer A) => any) ? A : never; const fn00 = (name: string, age: number, single: boolean) => true type test07 = Params<typ ...

My project in WebStorm encounters a setback due to the updated release of Typescript 5+

Recently, I had to upgrade my TypeScript version from 4.9.5 to 5.1.3 because one of the libraries I'm using made a fix that required a newer TypeScript version. After the update, TypeScript started throwing errors for console calls and React event di ...

Modify Twig template variable using AJAX

I'm attempting to dynamically reload a section of my HTML with new data fetched through AJAX. Within the code, there is a loop that iterates over clients: {% for client in clients %} After making an AJAX request and receiving updated client informa ...

The information retrieved from the database query is failing to appear on my webpage

I am encountering an issue where I am unable to display product details on my webpage in a specific format after submitting an ID number through a form. The query does not show any data when submitted. My objective is to append the latest retrieved data be ...

Is there a way to prevent selection of past dates and future times in a bootstrap DateTimepicker?

I am looking to restrict past dates when selecting a date and disable future times when selecting a time in datetimepicker. Although I have attempted the code below, it has not yielded the desired results. Please refer to this Fiddle link HTML : <d ...

Empty files following XML retrieval using node.js

Currently, I am using the below code snippet to retrieve Yahoo weather XML files: // This script needs request libraries. // npm install request var fs = require('fs'); var woeid_array = fs.readFileSync('woeid.txt').toString().split(" ...

What is the best way to generate a linked list from a JSON array?

I have a list of universities that I generated from a JSON file and now I want to create hyperlinks for each university in the list so that users can navigate to their respective university pages. HTML <ul data-bind="foreach: university"> <li ...

You can obtain the values of multiple div selections using jQuery

In a display with two columns, I want to be able to perform a common operation (such as delete) based on the selection of certain div IDs. If a user selects the div IDs participant_1, participant_4, participant_6 at the same time, I need to collect these ...

`I am facing issues with class binding in Vue 3 when using SwiperJS`

Currently, I am working with Vue 3 along with swiperjs. I have encountered a problem related to the v-bind:class behavior in my project. The issue arises when transitioning to the second slide, where the !h-auto class does not get applied as expected. St ...

Oops! An error occurred: Validation Error - Unable to convert value to ObjectID

SCENARIO: It appears that there might be an error in my Mongoose Model or in the parameters being passed to the route. As a newcomer to the angular2 architecture, I may have overlooked something obvious. ISSUE: ISSUE: ValidationError: CastError: Cas ...

The key is not applicable for indexing the type as expected

Here is the TS code I am working with: type Fruit = { kind: "apple" } | { kind: "grape"; color: "green" | "black" }; type FruitTaste<TFruit extends Fruit> = TFruit["kind"] extends "apple" ? "good" : TFruit["color"] extends "green" ? "good" : ...