如何模拟业力中模拟服务的失败?

时间:2016-11-17 11:56:51

标签: 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: 'test'
    }

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

在example.component.spec.ts中测试可观察的函数

// this test work corectly
it('Should set name property to "test"', () => {
    comp._cm.getData();
    expect(comp.name).toBe('test');  
}

it('Should set name property to undefined', () => {
    comp._cm.getData();
    expect(comp.name).toBe('undefined');  
}

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

1 个答案:

答案 0 :(得分:2)

您应该使用Observable创建Observable.create。有了这个,您可以控制何时应该发出错误。例如

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

另见: