Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 如何模拟karma中模拟服务的失败?_Unit Testing_Testing_Angular_Typescript_Karma Runner - Fatal编程技术网

Unit testing 如何模拟karma中模拟服务的失败?

Unit testing 如何模拟karma中模拟服务的失败?,unit-testing,testing,angular,typescript,karma-runner,Unit Testing,Testing,Angular,Typescript,Karma Runner,example.component.ts中的Obeservable函数 public name: string; this._cm.getData().subscribe( response => { this.name = response.name; }, error => { this.name = undefined; } 模拟服务 public _cm = { data: { name

example.component.ts中的Obeservable函数

public name: string;

this._cm.getData().subscribe(
    response => {
       this.name = response.name;
    },
    error => {
        this.name = undefined;
    }
模拟服务

public _cm = {
    data: {
        name: 'test'
    }

    getData(): Observable<any> {
        return Observable.of(this.data);
    }
}

但是我不知道如何模拟错误响应getData()

您应该使用
Observable.create创建
Observable
。这样,您就可以控制何时发出错误。比如说

public _cm = {
    error: false,
    data: {
        name: 'test'
    },
    getData(): Observable<any> {
        return Observable.create(observer => {
            if (this.error) {
                observer.error(new Error("Boo"));
            } else {
                observer.next(this.data);
            }
            observer.complete();
        })
    }
}
另请参见:


方法可行,但我必须更改:observer.onError to observer.error observer.onNext to observer.next observer.onComplete to observer.complete
public _cm = {
    error: false,
    data: {
        name: 'test'
    },
    getData(): Observable<any> {
        return Observable.create(observer => {
            if (this.error) {
                observer.error(new Error("Boo"));
            } else {
                observer.next(this.data);
            }
            observer.complete();
        })
    }
}
_cm.error = true;
// do test