网站搜索

单元测试 - 如何在 Karma 中模拟模拟服务的失败?


example.component.ts 中的可观察函数

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

你只需使用 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();
        })
    }
}

现在你可以在测试中控制错误了

_cm.error = true;
// do test

另请参阅:

  • Angular 2 - 在服务中使用可观察对象测试错误情况