Troubleshooting: Imported Variable in Angular 2+ Throwing Module Not Found Error

During my testing process, I encountered an issue when trying to require a .json file with data to perform checks on. Despite passing the string indicating where to find the file into the require function, it seems to be unsuccessful...

Success:

const data = require('../../../assets/data.json');

Failure:

const jsonUrl = '../../../assets/data.json';
const data = require(jsonUrl);

I prefer using the variable jsonUrl as this URL string will need to be utilized multiple times within the test. However, I am perplexed as to why it is not locating the file?


Clarification of Inquiry:

Considering that mocking is the recommended approach in this situation, and my lack of understanding in executing this effectively... I have decided to make some adjustments to the question for clarity.

To my understanding in testing, I believe that it is essential to read in the actual data being used for accurate testing outcomes. If my assumption is incorrect, kindly advise me accordingly.

The following are details of what I am examining...

data.json

[
  {
    "name": "one",
    "id": 1,
  },
  ...
  // This structure applies to around 20 entries
]

component.ts

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

loadData() {
   const statusUrl = '../../../assets/data.json';
   return this.httpClient.get(statusUrl);
}

test.ts The issue relates to 'cannot find module' due to the require problem mentioned earlier.

it('should load status data from local json', fakeAsync(() => {
    const jsonUrl = '../../../assets/status.json';
    const data = require(jsonUrl);
    const request = httpMock.expectOne(jsonUrl);
    request.flush(data);
    expect(component.status).toEqual(data);
  }));

Answer №1

The issue was resolved by ensuring it matched any object type:

it('should retrieve status data from local JSON file', fakeAsync(() => {
    const jsonUrl = '../../../assets/greyhound.status.json';
    const data = [];

    const request = httpMock.expectOne(jsonUrl);
    request.flush(data);
    expect(component.raceStatuses).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

What is the best approach: Referencing schema within properties or including it as an array in Mongoose?

Consider the scenario where we have two schemas, User and Post. Should we include a reference to User in Post's properties or should we add an array of Post schema inside User schema? Which approach is more efficient in terms of performance and other ...

Retrieve the JSON response from the server and store it in variables using jQuery's AJAX function with the `done

I am trying to retrieve a JSON response from the server upon clicking a button and then parse it into a div. However, I am struggling with how to accomplish this. <button type="submit" id="btPay" name="btPay"> Go for Pay ...

ReactJS aligns buttons to the right

I have been attempting to align a button to the far right without success. Here is what I have tried: <Button variant="contained" style={{display: 'flex', justifyContent: 'right'}} color="primary" className="float-right" onClick={ ...

Stopping the papaparse streaming process once a certain number of results have been achieved

Currently, I am utilizing the PapaParse library to parse a large CSV file in chunk mode. During my data validation process, I encountered an issue where I was unable to stop streaming the data once validation failed. I attempted to halt the streaming by ...

Get your hands on a PDF containing server node and vue.js

I am facing an issue with creating a secure download link for a PDF file on the server. When clicking on the link, the file is not being downloaded properly. Ensuring that the PDF link remains hidden from the client but still allows for downloading direct ...

Unable to import a Module in React without curly braces, even when using 'export default'

I recently stumbled upon a question regarding module imports in React. Some sources mentioned that using curly braces around imports can increase the bundle size by importing the entire library. However, I had been successfully importing modules without cu ...

AngularJS / Updating the URL only after the template's resolve property has been successfully resolved

Resolve plays a crucial role in preventing a template from being displayed based on certain conditional logic that deals with the result of a promise (whether it is solved or rejected). In my application, I implement it like this: .config(['$routePr ...

JavaScript enables users to store over 5 megabytes of data on their client devices

Is there a way to store more than 5mb in the client browser? I need this functionality across various browsers including Firefox, Chrome, Internet Explorer, Safari (iOS), and Windows Phone 8 Browser. Initially, localStorage seemed like a viable option as i ...

Unraveling nested JSON structures with varying formats in Javascript or Jquery: Step-by-step guide

var cart = [ { "Items": "", "category": "", "contents": [ { "Apple iPhone": "222", "French": "Bounjour", "id": 1234, "icon": "/images/bg.jpg", "callback": "use()", "pricetag":"false" } ] }, { "Items": "No 2" ...

emulating the behavior of a synchronous XmlHttpRequest

While I have taken the time to explore similar questions like Pattern for wrapping an Asynchronous JavaScript function to make it synchronous & Make async event synchronous in JavaScript, I want to ensure that I consider all potential solutions. Is it ...

What is the process for creating a PickByValue data type?

The TypeScript language comes with a built-in Pick type, which is defined as follows: type Pick<T, K extends keyof T> = { [P in K]: T[P]; }; If you were to create a custom PickByValue type, how would you implement it to achieve the following func ...

Modifying the delimiter used in paste range feature of ag-grid

Is there a way to enable pasting tab separated data into an ag-grid column instead of a row? Currently, when pasting newline separated data it goes into columns and tab separated goes into rows. The documentation suggests using the "clipboardDeliminator" ...

An Easy Guide to Incorporating react-cookie into TypeScript Projects

I am currently developing an application in React using the React template provided by Visual Studio 2017. My goal is to incorporate react-cookie into my project. After installing this library with the command: npm install react-cookie However, when I at ...

Angular progress bar with intermittent breaks

Currently developing an Angular application and looking to implement a progress bar similar to the one displayed in the linked images. https://i.sstatic.net/5doDu.png https://i.sstatic.net/SP2it.png Although there are multiple progress bars available on ...

Incorporating library files (css/js) into your app built on the angular-fullstack framework

After using a Yo Angular-Fullstack generator (https://github.com/DaftMonk/generator-angular-fullstack) to start an app, I attempted to install Toastr from bower with the command: bower install angular-toastr Now, I need to add the toastr css and js files ...

When using AngularJS, the templateUrl feature delays the initialization of the controller, causing issues with dependent code

Recently, I began experimenting with AngularJS and so far, everything seems to be going smoothly except for one small issue. Let's consider a scenario where I have two directives, with one directive relying on the other, like this: angular.module(&ap ...

Capturing mouse clicks in Javascript: a guide to detecting when the mouse moves between mousedown and mouseup events

I have been working on a website that features a scrolling JavaScript timeline, inspired by the code found in this tutorial. You can check out the demo for this tutorial here. One issue I've encountered is when a user attempts to drag the timeline an ...

Eliminate the commas when listing Google Places types

I am currently utilizing the Google Places API and came across these code snippets at https://developers.google.com/maps/documentation/javascript/examples/place-search-pagination. var map, placesList; function initialize() { var pyrmont = new google.ma ...

Error: The specified property is not found in type 'never' - occurring with the ngFor loop variable

When working with API responses and dynamically sorting my view, I utilize an ngFor loop. Here's the snippet of code in question: <agm-marker *ngFor="let httpResponses of response" [latitude]= "httpResponses.lat" [longitude]=& ...

Where can the npm script find the files in package.json for angular 2.x?

Currently working in a Windows 7 environment using Chrome with Angular 2.4 (without Visual Studio), I successfully downloaded the quickstart. Now, I need to determine the version of 'node' that I am utilizing, so I input node -v in the command p ...