angularjs2 test在karma / jasmine中可观察到

时间:2016-04-07 14:10:47

标签: angularjs observable

根据http客户端教程(https://angular.io/docs/ts/latest/guide/server-communication.html),我创建了一个简单的Web服务。该服务在浏览器中运行:

import {Injectable} from "angular2/core";
import {Http} from "angular2/http";
import {Response} from "angular2/http";
import {Observable} from 'rxjs/Observable';


@Injectable()
export class XMLService {
    constructor(private _http:Http) {

    }

    private _xmlUrl:string = 'resources/mocks/example_xml_string/minimal.xml';

    public getXML() {
        console.log("service called");
        return this._http.get(this._xmlUrl)
            .map(this.mapXML)
            .catch(this.handleError);
    }

    private mapXML(response:Response){
        console.log("mapping called");
        return <string> response.text();
    }

    private handleError(error:Response) {
        console.log("error called");
        console.log(error);
        return Observable.throw(error.json().error || 'Server error');
    }

}  

我还根据ng-test-seed基础设施(主要按预期工作)编写了一个测试:

import { it, xit, iit, describe, expect, inject, injectAsync, beforeEachProviders, fakeAsync, tick } from 'angular2/testing';
import {XMLService} from "../../../../../app/de/q21/europass/service/xml.service";
import {HTTP_PROVIDERS} from "angular2/http";
import {Http} from "angular2/http";
import {Response} from "angular2/http";
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';



describe('xml service', () => {
    beforeEachProviders(() => [XMLService, Http, HTTP_PROVIDERS]);

    it('should get an europass xml string', inject([XMLService], fakeAsync((xmlService) => {

        var xmlResult="";
        var xmlError = "";
        xmlService.getXML()
            .subscribe(
                result =>
                    xmlResult = result
                ,
                error => {
                    xmlError = <any>error;
                    console.log("Error: " + error)
                }
            );

        console.log("result: "+ xmlResult);


    })));
});

测试工作正常,服务开始通过xhr获取.xml,但结果为空。可能在文件传输之前测试结束了吗?

任何想法如何解决这个问题?

汤姆

0 个答案:

没有答案