Checking the successful loading of JSON data in Angular2+ by following these steps:

I am struggling to write a test for an Angular method that loads the contents of a locally stored JSON file featuring an array.

test.ts (trimmed for brevity)

describe('MyComponent', () => {

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [HttpClientTestingModule],
    });

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;

    component.ngOnInit();

  it('should load status data from local json', () => {
    const data = require('../../../assets/myData.json');
    component.getThings();
    expect(component.data).toEqual(data);
  });
}

MyComponent.ts

data: string[];

constructor(private httpClient: HttpClient) {}

ngOnInit() {
   this.getThings().subscribe(data =
       this.data = data;
   }
}

getData(): Observable<any> {
    const data = '../../../assets/data.json';
    return this.httpClient.get(data);
  }

Answer №1

When conducting testing on HTTP requests, it is important to simulate the request.
Learn more about HttpClientTestingModule below:
https://angular.io/api/common/http/testing/HttpClientTestingModule
https://medium.com/spektrakel-blog/angular-testing-snippets-httpclient-d1dc2f035eb8

The provided code below is operational, with some updates made to the component code:
Component:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-load-local-file',
  templateUrl: './load-local-file.component.html',
  styleUrls: ['./load-local-file.component.css']
})
export class LoadLocalFileComponent implements OnInit {

  data: string[];

  constructor(private httpClient: HttpClient) { }

  ngOnInit() {
    this.getData().subscribe(data => {
      this.data = data;
    });

  }

  getData(): Observable<any> {
    const data = './data.json';
    return this.httpClient.get(data);
  }

}

Spec:

  import { TestBed, async, fakeAsync, tick } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'
import { LoadLocalFileComponent } from 'src/app/load-local-file/load-local-file.component';

describe('MyComponent', () => {
  let fixture, component, httpMock: HttpTestingController;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [LoadLocalFileComponent],
      imports: [HttpClientTestingModule]
    });

    fixture = TestBed.createComponent(LoadLocalFileComponent);
    component = fixture.componentInstance;
    httpMock = TestBed.get(HttpTestingController);

  }));

  it('should load status data from local json', fakeAsync(() => {
    const data = require('./data.json');

    component.ngOnInit();
    tick();
    const request = httpMock.expectOne('./data.json');
    request.flush(data);
    expect(component.data).toEqual(data);
  }));

});

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

Understanding the Functioning of a Digital Analog Clock Using JavaScript

As a new learner, I found the operation of a Digital analog clock to be quite puzzling. I was presented with an image called clock.png, and I specifically struggled with how the hands of the clock function. Javascript - const deg = 6; // defining the valu ...

Undefined is the value assigned to Javascript Dot Notation

When using dot notation to access objects with a '.', I am encountering an issue that I cannot seem to figure out. The success function in my jQuery $.ajax function looks like this: success: function(data){ console.log('data = ' + da ...

Error in TypeScript when using Google Maps React with Next.js: there is a possibility that infoWindow.close is undefined

Working on a small project in next.js (typescript) utilizing the google maps api with a KmlLayer. I want my map to interact with another component, SensorInfo. The current setup allows for smooth interaction between them - when SensorInfo is closed, the in ...

What could be causing worker threads to fail when instantiating a class from a separate file?

The following TypeScript file is being used: import { Worker, WorkerOptions, isMainThread, parentPort } from "worker_threads"; import path from "path"; export class SimpleWorker { private worker: any; constructor() { i ...

Storing a URL as a unique identifier within Chrome's local storage repository

I am facing an issue with storing a list of values in Chrome's local storage for a Chrome extension. I am trying to use the URL as the key in the key-value store, but for some reason, the set() function fails when using a URL as a key. Surprisingly, w ...

Screen JSON data by applying filters

In my current project, I am working on extracting data from a JSON file and presenting it to the user in a way that allows them to input values that match the expected data. My goal is to show different sections of the screen at different times. The initi ...

send form information to the server's controller through an AJAX request

Seeking assistance to pass data from the <input> value and corresponding recordID to a controller method for each item in my shopping cart. I have implemented a for loop that generates an input field for each item within the cart, as shown below: &l ...

Adding a modifier to multiple elements within an object

My document structure includes the following: { _id: ..., name: ..., keywords: { group_a: [1, 2, 5], group_b: [4, 7, 6] } } I've figured out how to add elements to one of the elements in the keywords object like this: db.coll.update ...

Accessing environmental variables from pug template

Currently, I am utilizing pug to generate static HTML for my own customized static site builder. In my package.json file, the only line of Node.js server code present is: "watch-pages": "pug -O options.json -w pages/ --out _static-website/" However, the ...

Preserve the Browser Scroll Position when navigating to another page

Currently tackling a challenge with JS, JQuery, and PHP where I'm attempting to resolve an infinite scroll issue. The specific problem arises when scrolling down the page extensively while loading more pages via ajax, then navigating to a different pa ...

Struggling to concentrate using jQuery?

When the search icon is clicked, I want the focus to be on the input so the user can start typing right away without having to manually click on it. Although I tried using focus(), it doesn't seem to work for this particular input. $('.header__ic ...

"Modifying a variable within an object while iterating through a loop

I am attempting to update a variable within an object while looping through the elements. Specifically, I am targeting all parent elements with the class "parent" to use with the ScrollMagic plugin. Here is my code: var childElement = $('.child' ...

Is there a way to define the width of an element within the display:flex property in CSS?

Could you please review the following: https://codepen.io/sir-j/pen/dyRVrPb I am encountering an issue where setting the input [type=range] to 500px doesn't seem to make a difference from 100px, 500px, or 800px. This leads me to believe that display ...

Creating, editing, and deleting data in Ng2 smart table is a seamless process that can greatly enhance

While working on my Angular 2 project, I utilized [ng2 smart table]. My goal was to send an API request using the http.post() method. However, upon clicking the button to confirm the data, I encountered the following error in the console: ERROR TypeErro ...

Using THREE.js to pass an array of vec2 to a shader

I've spent quite some time browsing the internet but haven't found the right solution yet. I came across a list of uniform types used by THREE.js and believe the code below should be accurate. I'm defining a uniform array of Vector2 at the ...

Navigating through a large array list that contains both arrays and objects in Typescript:

I have an array containing arrays of objects, each with at least 10 properties. My goal is to extract and store only the ids of these objects in the same order. Here is the code I have written for this task: Here is the structure of my data: organisationC ...

Challenges encountered in configuring system tests with Capybara and Selenium on a Rails 5.1 application (recently migrated from Rails 4)

I am currently in the process of setting up system tests using Capybara and Selenium for a Rails 5.1 application that was previously upgraded from Rails 4. Here is a summary of what I have accomplished so far. In the Gemfile within group :development, :te ...

What is the reason behind encountering these errors while trying to run my Gatsby development server?

I'm currently working on the part three tutorial provided by Gatsby on their official website and I've encountered a problem. Upon executing the command gatsby new tutorial-part-three https://github.com/gatsbyjs/gatsby-starter-hello-world I rec ...

Retrieving specific object properties within an Angular 2 and Ionic 2 form

Within the @Page, I have a few select inputs. In addition to storing the value of the selected option, such as {{project.title}}, I also require the ability to return another selected object property, such as {{project.id}} or even the entire object. When ...

NG build error: Module parsing failed due to an unexpected token - no updates made

Two days ago, out of nowhere, we started encountering build errors during deployment using GitLab CI. No alterations have been made to the build scripts, and none of the versions of NPM, NG, or Angular have been modified. The same compilation commands cont ...