Angular 2 Testing: “Unable to find variable: headers” when testing with PhantomJS, but works fine with Chrome

My team and I recently started creating a project using angular-cli 1.1.1 (angular 4.1.3), and we included an in-memory-web-api from angular.io hero tour to mock http calls until our api will be built. I was able to get all of our karma modulation tests to successfully pass chrome, but due to CI limitations who wanted to try and get karma working with PhantomJS. When switching from chrome to phantomJS, several tests do not allow to indicate an error message:

PhantomJS 2.1.1 (Mac OS X 0.0.0) UserDataService should be created FAILED
    ReferenceError: Can't find variable: Headers in http://localhost:9876/_karma_webpack_/main.bundle.js (line 693)

Here is what my user-data.service.ts file looks like :

import {Injectable} from @angular/core";
import {Http} from "@angular/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/catch";
import "rxjs/add/operator/toPromise";
import "rxjs/add/operator/find";
import {User} from "../data-objects/user";
import {Observable} from "rxjs/Observable";

@Injectable()
export class UserDataService {
  private userDataUrl = `api/userData`;
  private headers = new Headers({"Content-Type": "application/json"});
  constructor(private http: Http) { }

  getUser(id:number): Observable<User> {
    const url = `${this.userDataUrl}/?id=${id}`;
   return this.http.get(url, this.headers)
      .map(response => {
        return  response.json().data as User;
      })
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error("An error occurred in the user data service.", error);
    return Promise.reject(error.json().error || "Server Error in UserDataServer")
  }
}

, , phantomJS , . karma.conf.js user-data.service.spec.ts . .

karma.conf.js

  module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-phantomjs-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular/cli/plugins/karma')
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    files: [
      { pattern: './src/test.ts', watched: false },
      { pattern: 'node_modules/angular-in-memory-web-api/**/*.js', included: false, watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['@angular/cli']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    coverageIstanbulReporter: {
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      config: './angular-cli.json',
      environment: 'dev'
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
              ? ['progress', 'coverage-istanbul']
              : ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_DEBUG,
    autoWatch: true,
    // browsers: ['ChromeHeadless'],
    browsers: ['PhantomJS'],
    // browsers: ['Chrome'],
    singleRun: false
  });
};

User-data.service.spec.ts:

import {TestBed, inject} from '@angular/core/testing';

import {UserDataService} from './user-data.service';
import {Http, BaseRequestOptions} from "@angular/http";
import {MockBackend} from "@angular/http/testing";


describe('UserDataService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [UserDataService,
        MockBackend,
        BaseRequestOptions,
        {provide: Http}]
    });
  });

  fit('should be created', inject([UserDataService], (service: UserDataService) => {
    expect(service).toBeTruthy();
  }));
});
+4
1

main.bundle.js, . intellij , , lib.es6.d.ts, @angular/http. angular, , phantomJS, .

+6

Source: https://habr.com/ru/post/1679282/


All Articles