【问题标题】:Angular 2 Testing: "Can't find variable: Headers" when testing with PhantomJS but works fine with ChromeAngular 2 测试:使用 PhantomJS 进行测试时“找不到变量:标头”,但在 Chrome 中运行良好
【发布时间】:2017-11-17 00:58:47
【问题描述】:

我和我的团队最近开始使用 angular-cli 1.1.1 (angular 4.1.3) 构建一个项目,我们正在合并 angular.io 的英雄之旅中的 in-memory-web-api 来模拟 http 调用,直到我们的 api建。我能够使用 chrome 成功通过我们所有的业力单元测试,但由于 CI 限制,我想尝试使用 PhantomJS 运行业力。从 chrome 切换到 phantomJS 时,一些测试失败,指定错误消息:

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)

这是我的 user-data.service.ts 文件的样子:

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 无法找到标题但 chrome 可以。为了完整起见,这里分别是我的 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();
  }));
});

【问题讨论】:

    标签: angular unit-testing google-chrome phantomjs karma-jasmine


    【解决方案1】:

    在查看发生错误的 main.bundle.js 文件后,我找到了答案。使用 intellij 为我管理导入,我意识到标头是从 lib.es6.d.ts 而不是从 @angular/http 中提取的。一旦我包含了从 angular 导入的 Headers,我在 phantomJS 中失败的所有测试都开始通过了。

    【讨论】:

    • 确实没有任何代码可显示,我遇到的问题与导入错误的名为 Header 的类有关。我是从 lib.es6.d.ts 而不是 @angular/http 导入的。我通过更正 import 语句来解决这个问题,它看起来像: import {Headers, Http} from "@angular/http";而不是从“@angular/http”导入 {Http};我的 IDE 会自动导入名为 Header 的 ES6 类,直到发布问题后我才注意到。
    • 好的,我明白了。我什至不使用它,但我收到了警告。无论如何感谢您的回复
    猜你喜欢
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    相关资源
    最近更新 更多