(Angular 2 + Jasmin)如何测试调用服务的组件内的方法?

时间:2017-03-29 19:21:49

标签: angular jasmine karma-jasmine

任何人都可以帮助我如何使用Jasmine创建一个测试到我的组件下面?我正在使用" Observable"。

test.service.ts

export class TestService {
http: Http;
headers: Headers;
apiRoot: string = 'service/';

    constructor(http: Http) {
        this.http = http;
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');
    }

    getVersion(): Observable<string> {
        return this.http.get('version.txt').map(data => data.text());
    }
}

我想测试方法&#34; loadVersion&#34;叫服务。我还需要测试成功和错误案例。

test.component.ts

import { Component } from '@angular/core';
import { TestService } from './test.service';

@Component({
  selector: 'app-root',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent {
  service: TestService;
  version: string;
  today: number = Date.now();

  constructor(service: TestService) {
    this.service = service;

    this.loadVersion();
  }

  loadVersion() {
    this.service.getVersion()
      .subscribe(data => {
        this.version = data;
      }, error => {
        console.log('error', error);
      });
  }
}

谢谢!

0 个答案:

没有答案