使用Karma为Typecript运行Angular 2测试

时间:2016-04-29 13:41:32

标签: typescript angular gulp karma-runner karma-jasmine

我试图使用业力来测试Angular 2 Typescript代码。我有两个虚拟测试。一个人测试是否真的&#39; equals&#39; true&#39;,另一个从AppComponent调用返回硬编码字符串的方法。当我删除第二个测试用例并且仅通过var request = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress, endpoint)); SetHeaders(request); if (string.IsNullOrEmpty(authToken)) { throw new AuthTokenNullException(); } request.Headers["Cookie"] = authToken; request.Method = "GET"; HttpWebResponse response = request.GetResponseAsync().Result as HttpWebResponse; if (!response.StatusCode.Equals(HttpStatusCode.OK)) { throw new HttpRequestException(string.Format("Warning expected response as 200 and got {0}", Convert.ToString(response.StatusCode))); } var reader = new StreamReader(response.GetResponseStream()); string stringResponse = reader.ReadToEnd(); return JsonConvert.DeserializeObject<T>(stringResponse); 运行第一个测试用例时,它将打开浏览器,运行测试并且它将起作用。当我添加第二个测试时,它会给我一个错误。 的 AppComponent.ts

npm test

AppComponent.spec.ts

///<reference path="../../node_modules/angular2/typings/browser.d.ts"/>
import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    templateUrl: 'partials/app.html',
})

export class AppComponent {

  response(text:string):any {
        return 'hello';
    }
}

当我运行/// <reference path="../../node_modules/angular2/typings/browser.d.ts" /> /// <reference path="../../typings/main/ambient/jasmine/index.d.ts" /> import {it, describe, expect, beforeEach, inject} from 'angular2/testing'; import {AppComponent} from "./app.component"; describe('First Test', () => { let component: AppComponent; it('Value of testvar should be test', () => { expect(true).toEqual(true); }); }); describe('Second Test', () => { let component = new AppComponent(); it('value must be true', () => { expect(component.response('hi').toEqual('hello')); }); }); 时,它会启动浏览器并且会出错。控制台输出在这里:

npm test

3 个答案:

答案 0 :(得分:0)

我会尝试以下方法:

import {it, describe, expect, beforeEach, inject} from 'angular2/testing';
import {AppComponent} from "./app.component";

describe('Tests', () => {
  let component: AppComponent = new AppComponent();

  it('Value of testvar should be test', () => {
    expect(true).toEqual(true);
  });

  it('value must be true', () => {
    expect(component.response('hi').toEqual('hello'));
  });
});

答案 1 :(得分:0)

我遇到了这个问题 - 尽管错误信息相当无用,但根本原因是karma.conf.js文件数组中的错误路径。验证所有路径是否正确并且应该(可能?)清除。

答案 2 :(得分:0)

有同样的问题

29 07 2016 13:27:03.298:WARN [web-server]: 404: /base/dist/vendor/ts-md5/dist/dist/md5.js
Missing error handler on `socket`.
TypeError: (msg || "").replace is not a function

通常在路径中发布或错误import。在我的情况下,它发生是因为system-config.ts

中模块路径中的额外斜杠

当时

/** Map relative paths to URLs. */
const map: any = {
  'ts-md5': 'vendor/ts-md5/',

正确

/** Map relative paths to URLs. */
const map: any = {
  'ts-md5': 'vendor/ts-md5', // <- no slash now