Encountering a 404 error with Angular 2 Jasmine XHR while initializing a constructor

I have been diligently following the official Angular 2 tutorials on setting up unit testing using Jasmine. My goal is to mock a Profile object that is defined in another class. However, whenever I attempt to instantiate Profile using its constructor, an error appears in the web console stating "error loading file."

profile.ts

import {Injectable} from 'angular2/core';

export class Profile {
    id: number;
    name: string;
}

Unit-test.html

<html>
<head>
  <title>Jasmine Tests</title>
  <link rel="stylesheet" href="../node_modules/jasmine-core/lib/jasmine-core/jasmine.css">
  <script src="../node_modules/jasmine-core/lib/jasmine-core/jasmine.js"></script>
  <script src="../node_modules/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
  <script src="../node_modules/jasmine-core/lib/jasmine-core/boot.js"></script>
</head>
<body>
  <!-- #1. add the system.js and angular libraries -->
  <script src="../node_modules/systemjs/dist/system.src.js"></script>

  <script>
    // #2. Configure systemjs to use the .js extension
    //     for imports from the app folder
    System.config({
      packages: {
        'app': {defaultExtension: 'js'}
      }
    });

    // #3. Import the spec file explicitly
    Promise.all([
      System.import('profile.spec.js')
    ])
          // #4. wait for all imports to load ...
      //     then re-execute `window.onload` which
      //     triggers the Jasmine test-runner start
      //     or explain what went wrong
    .then(window.onload)
    .catch(console.error.bind(console));
  </script>
</body>
</html>

profile.spec.ts

import {Profile, ProfileService} from '../app/profile';

var guy: Profile = new Profile();

describe("Initialising Profile", function() {
    it("ID", function() {
        expect(guy.id).toBe(1);
    });

    it("Name", function() {
        expect(guy.name).toBe("Notguy");
    });
});

Web console error:

GET XHR http://127.0.0.1:8080/app/profile
    [HTTP/1.1 404 Not Found 1ms]
    Error: XHR error (404 Not Found) loading http://127.0.0.1:8080/app/profile
        Error loading http://127.0.0.1:8080/app/profile as "../app/profile" from http://127.0.0.1:8080/test/profile.spec.js
    Stack trace:
    error@http://127.0.0.1:8080/node_modules/systemjs/dist/system.src.js:1020:16
    bootstrap/</fetchTextFromURL/xhr.onreadystatechange@http://127.0.0.1:8080/node_modules/systemjs/dist/system.src.js:1028:13

The console does not raise any errors when I refrain from calling the constructor.

Your assistance in resolving this issue would be greatly appreciated.

EDIT: Directory structure has been simplified

root/
├── app
│   ├── boot.js
│   ├── boot.js.map
│   ├── boot.ts
│   ├── profile.js
│   ├── profile.js.map
│   ├── profile.ts
├── index.html
├── node_modules
├── npm-debug.log
├── package.json
├── test
│   ├── profile.spec.js
│   ├── profile.spec.js.map
│   ├── profile.spec.ts
│   └── unit-tests.html
└── tsconfig.json

Answer №1

To optimize the SystemJS configuration, I would make the changes outlined below:

<script>
  System.config({
    packages: {
      'app': {
        defaultExtension: 'js',
        format: 'register'
      },
      'test': {
        defaultExtension: 'js',
        format: 'register'
      }
    }
  });

  Promise.all([
    System.import('test/profile.spec')
  ])
  .then(window.onload)
  .catch(console.error.bind(console));
</script>

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

Security concern regarding XSRF in Spring and Angular 5

For my current project, I am using Spring as the backend (generated with microservices with Jhipster) and Angular5 as the frontend. On the server side, CSRF security is added (it was enabled by default when we created microservices with Jhipster). Workin ...

Is it possible to verify .0 with regular expressions?

In my project, I have a field that requires whole numbers only. To validate this, I used a regex validation /^\d{1,3}$/ which successfully validates whole number entry and rejects decimal points starting from .1. However, I encountered an issue where ...

Getting a JSON value and saving it to a variable in Angular 4

Here is the JSON structure: { "Semester": [ { "queueName": "Science", "totalCount": 300, "unassignedCount": 10, "subjectDetails": [ { "subjectName": "Chemistry", "sectionOne": 100, "secti ...

How can I deploy a react-express application to Azure cloud platform?

Struggling to deploy my react-express application on Azure. The code is divided into client and server directories. Attempted deployment using Azure Static Web application but encountered failure. https://i.stack.imgur.com/ailA0.png https://i.stack.imgur.c ...

Angular encounters issue when retrieving CSS file while navigating to a nested route

When trying to access a child component directly in production mode (using ng serve --prod), it fails to load the CSS file as it attempts to fetch it from a nested path. For example, when navigating to "localhost:4200/doc/", the CSS Request URL is: loca ...

Invalid index type: Cannot use type 'Number' as an index

When working with TypeScript, I encountered an issue with using an array as a map to access another array of objects. Below is a simplified snippet of my code: var mp : Number[] = [1, 2, 0]; var arr : any[] = ['a', 4, /regex/]; console.log(arr[m ...

Stepper that is vertical combined with table information

I am currently facing a unique challenge with a component I'm trying to create. It's a combination of a vertical Stepper and a Datagrid. My goal is to group specific table sections within the content of a vertical Stepper, purely for data visual ...

Display a message stating "No data available" using HighCharts Angular when the data series is empty

My Angular app utilizes Highchart for data visualization. One of the requirements is to display a message within the Highchart if the API returns an empty data set. I attempted a solution, but unfortunately, the message does not appear in the Highchart a ...

What is preventing Ionic from locating my model interface?

I recently started working with Ionic and I am using a tutorial as a guide to integrate Firebase authentication into my project. However, I am encountering an issue with the user interface that is being generated. When I run ionic serve for the first time ...

Unexpected error encountered in Angular 2 beta: IE 10 displays 'Potentially unhandled rejection [3] SyntaxError: Expected'

Question regarding Angular 2 Beta: I am starting off with a general overview in the hopes that this issue is already recognized, and I simply overlooked something during my research. Initially, when Angular 2 Beta.0 was released, I managed to run a basic m ...

npm encountered a 401 Unauthorized error while trying to access the latest version of @angular/cli

When attempting to run the npm install -g @angular/cli command in admin mode from the command window, I encountered the error message: npm ERR! 401 Unauthorized: @angular/cli@latest A colleague of mine did not face any issues with this command, and I hav ...

Troubleshooting the lack of success in enhancing global scope within Typescript

Currently, I am working on a microservices application where I have two very similar services that use practically the same packages. To perform some testing, I decided to add a function to the global scope and modified it slightly to prevent any TypeScrip ...

Reading JSON in Spring Boot can sometimes be challenging, especially when faced with errors like "Cannot deserialize value of type `X` from Array value." This error typically occurs when trying to parse an array value

I am facing an issue with sending data from my Angular application to SpringBoot. The problem arises when the server does not receive the correct object that is being sent. Upon checking the console.log output for what is being sent to the server, everyth ...

Issue when retrieving child elements in Next.js server-side component

"use client"; -- Imports and interfaces const SubscriptionDataFetcher: React.FC<SubscriptionDataFetcherProps> = ({ children }) => { const [data, setData] = useState<SubscriptionData>({}); -- Functions return <> ...

What is the rationale behind permitting surplus properties in Typescript interfaces even though all properties are declared as optional?

Exploring the code snippet... interface Options { allowed?: string; } function test(options: Options) { return options; } const options = { allowed: 'allowed', notAllowed: 'notAllowed', }; test(options); // no error thrown ...

How to Utilize Knockout's BindingHandler to Integrate JQuery.Datatables Select Feature?

I've developed a custom KO bindingHandler (view it here) to assist in updating the DataTable. The documentation for JQuery.DataTable.Select regarding how to access data requires a handle. You can see the details here. var table = $('#myTable&a ...

Managing Scroll Behavior in Ionic

I'm in the process of developing a quiz application using Ionic and Angular. My goal is to display one card at a time, similar to how Instagram and Facebook do it. This means that as users scroll down the app, only one card should be visible on their ...

Lazy loading Google Analytics script in Angular: A step-by-step guide

Currently I am working with Angular 8 and I am interested in lazily loading my Google Analytics script. I came across some documentation that mentioned globally loading scripts lazily using the script array in angular.json: "scripts": [ "src/global-scri ...

Using Angular/Typescript to interact with HTML5 Input type Date on Firefox (FF)

Are there any Angular/Typescript projects that are completely built without relying on third-party libraries? I am encountering problems with Firefox and IE11. It works fine on Chrome where the value can be read, but the calendar does not display when us ...

What is the process for defining a global variable within a module in Typescript?

I've already included a global value in my global JavaScript context: const fs = require('fs') For a specific reason, I need to include it in the global scope. Now, I want to create a .d.ts file to declare the global variable with a stron ...