mardi 1 mars 2016

Angular 2 Jasmine XHR error 404 not found when calling constructor

I've been following the official tutorials to set up unit testing in Angular 2 using Jasmine. I want to mock a Profile object defined in another class. The web console displays an error when I try to instantiate Profile using its constructor; it states 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 = { "id": 1, "name": "Guy" }

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://ift.tt/1SgDnUt
    [HTTP/1.1 404 Not Found 1ms]
    Error: XHR error (404 Not Found) loading http://ift.tt/1SgDnUt
        Error loading http://ift.tt/1SgDnUt as "../app/profile" from http://ift.tt/1QpVN0i
    Stack trace:
    error@http://ift.tt/1SgDn6M
    bootstrap/</fetchTextFromURL/xhr.onreadystatechange@http://ift.tt/1QpVK4D

The console does not complain when I don't call the constructor.

Any help will be much appreciated.

Aucun commentaire:

Enregistrer un commentaire