Within an Angular test scenario, execute a static method from a service that triggers an HTTP get request to fetch stored JSON data. This data is then retrieved and returned back to the service

Currently, I am facing a challenge in my Angular test case where I am trying to load JSON data via an HTTP call.

  • The issue arises when a static method is called from a service spec file named "url-service.spec" to another service named "load-json.service.spec".
  • In the "load-json.pservice.spec" service, an HTTP get request is made to fetch the JSON data, and the subscription happens within that method. The JSON data is then returned, but it does not return an observable back to url-service.

I have tried using spyOn for calling the static method, but I am struggling to inject HTTP, load the JSON, and subscribe within that context.

Any guidance or assistance on this matter would be greatly appreciated. Thank you in advance!

Answer №1

Allow me to provide an illustration from a recent project of mine. This example could potentially give you some insights.

describe("Employee feedback platform", () => {
let httpServiceMock: jasmine.SpyObj<HttpClient>;
let feedbackPlatform: FeedbackPlatform;

 beforeEach(() => {
 const apiEndpointServiceSpy = jasmine.createSpyObj('ApiEndpointBuilderService', ['buildApiResponse']);
 httpServiceMock = jasmine.createSpyObj('HttpClient', ['patch']);
feedbackPlatform = new FeedbackPlatform(httpServiceMock, apiEndpointServiceSpy);
});

it('should submit employee feedback and receive confirmation response', (done: DoneFn) => {
const expectedConfirmationData: ConfirmationData = { id: 5678, message: "Feedback submitted successfully" };

httpServiceMock.patch.and.returnValue(asyncData(expectedConfirmationData));

 feedbackPlatform.submitEmployeeFeedback(9876, "Positive feedback for team leader").subscribe({
  next: confirmData => {
    expect(confirmData).withContext("Anticipating confirmation data").toEqual(expectedConfirmationData);
    done();
  },
  error: done.fail
});

 expect(httpServiceMock.patch.calls.count()).withContext('one call').toBe(1);   
});   
});

Answer №2

You may need to approach the problem differently as it seems you are heading in the wrong direction. I recommend mocking the method found in "load-json.service.ts". The mocked method should accurately return the JSON data.

If you are conducting tests on certain components, here is a suggestion that might be helpful.

Pay attention to the providers section where we are instructing the component to utilize our mocked LoadJsonService.

...
const jsonDataObj = {foo: 'bar'};
const mockedLoadJsonService = {
  getJson:()=> JSON.stringify(jsonDataObj)
}

beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        ...
      ],
      declarations: [...],
      providers: [
        { provide: LoadJsonService, useValue: mockedLoadJsonService },
      ],
    }).compileComponents();
  });

...

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

Enhancing Array values within a Hashmap in JavaScript: Tips for Adding more Items

Is there a 'bar' key in the hashmap that has an array as its value with only one item ['foo']? I want to add another item, 'foo1', to the same array. Is the following code the right approach, or is there a simpler way to achie ...

What is the term used for the objects that res.render passes?

I constantly find myself struggling with defining objects inside res.render. Is there a way to define them globally or outside of res.render? I hope someone can offer some guidance.. here is a sample code snippet: router.get("/home/blog", function(req,r ...

Transfer all specified resources from one stack to another in AWS CDK

In the process of creating two stacks, I aim to reference the resources from the first stack, such as Lambda, API Gateway, and DynamoDB, in the second stack without hard coding all the resources using Stack Props. Please note: I do not want to use Stack Pr ...

Navigate to the logout page automatically when closing the final tab

In order to comply with the requirement, I need to log out the user when they close the last tab on the browser. ngOnInit() { let counter: any = this.cookieService.get('screenCounterCookie'); counter ? ++counter : (counter = & ...

Issues arise with the escape key functionality when attempting to close an Angular modal

I have a component called Escrituracao that handles a client's billing information. It utilizes a mat-table to display all the necessary data. When creating a new bill, a modal window, known as CadastrarLancamentoComponent, is opened: openModalLancame ...

Checking whether a node stream operates in objectMode

When working with a node js stream object, how can I ascertain if it is an object stream in objectMode? For example, suppose I have a readable stream instance: const myReadableStream = new ReadableStreamImplementation({ options: { objectMode : true } ...

The `Click()` functionality experiences malfunction in Protractor automation scripts

I am currently automating my tests using Protractor and Appium for an AngularJS website with the Jasmine framework in an iPad simulator. Although the sendkeys() function is working fine for entering the username and password, I am facing issues when clicki ...

Why bother re-rendering components in React that haven't had any changes in their state?

Within my main component, I have both a state and a static component nested inside. An issue arises when the state changes and triggers a re-render of the main component, causing the static component to also re-render unnecessarily. import { useState } fro ...

Retrieve Image URL from RSS Medium Feed

I am attempting to showcase the images from each post in medium's RSS feed using only JavaScript or Angular, without relying on JQuery. I am able to retrieve the title, creation date, and link for each post. Currently, I am developing with Ionic2. en ...

Executing JavaScript in HttpClient or HtmlUnitHow to trigger javascript in HttpClient or HtmlUnit

Currently, I am using the HttpClient POST method to perform a specific action on a website. This involves using Javascript for an ajax connection which generates a unique requestID in the form of var reqID = Math.floor(Math.random()*1000001);. I need to ac ...

JavaScript autostop timer feature

An innovative concept is the solo cookie timer that holds off for one hour before resuming its function upon user interaction. No luck with Google. https://jsfiddle.net/m6vqyeu8/ Your input or assistance in creating your own version is greatly appreciate ...

What is the reason for multiple ajax functions being triggered when submitting a form through ajax?

I have a Drupal form with an AJAX submit. Additionally, I have another jQuery $.get function that sends a request every 2 minutes and inserts the response into an HTML element. The form and this JavaScript code are independent of each other, performing sep ...

Attempting to unveil concealed download URLs

Trying to extract download links from a website, but the format is as follows: <form action="" method="post" name="addondownload" id="addondownload" > <input type="hidden" name="addonid" id="addonid" value="2109" /> <input class="re ...

Tips for enhancing the contents of a single card within a react-bootstrap accordion

Currently, I am facing an issue with my columns expanding all cards at once when utilizing react-bootstrap accordion. My goal is to have each card expand individually upon clicking on its respective link. However, I am encountering difficulties in implem ...

Deleting a specific row within a Material UI DataGrid in Reactjs: Tips and tricks

As I embark on this React project, things are progressing smoothly. However, a challenge has arisen. The functionality I aim for is as follows: When the checkbox in a row is clicked, I want that particular row to be deleted. For instance, selecting checkb ...

Running a command once the forEach loop is completed in Angular

Within the HTML, I have a function that is triggered by an ng-click: vm.items = []; vm.moveItems = function() { angular.forEach(vm.items, function (item) { $http({ method: 'PUT', url: &apos ...

Struggling with using Redux with tassign in Angular (typescript) to combine state.array and action.array. However, encountering an issue where state.array.join is not a function

Redux function to combine all videos: function combineAllVideos(state, action) { return tassign(state, { allVideos: state.allVideos.concat([action.data]) }); } Declaration + State for all videos array: allVideos: Array<Object>; OR allVid ...

What is the correct way to access an element with spaces in handlebars while working with node.js?

I have an object containing values with spaces in strings. For example: object = { "group of people": [ { (...) } ], "another group of people": [ { (...) } ] } Now, I want to use this object with the handlebars helper block in my view ( ...

Styling the sub-elements using CSS in JavaScript

Currently, I am dealing with two CSS classes: .dragbox and .removebutton. The .dragbox represents a div, while the .removebutton is a button nested within the div. On my page, there are multiple dynamically generated instances of .dragbox. I am seeking ...

Avoiding content resizing when using a drawer in Material UI

My project features a drawer that expands, but I am encountering an issue where the content inside the drawer resizes when expanded. However, this is not the desired outcome. I want the expanded drawer to overlay the content without resizing it. How can I ...