gpt4 book ai didi

unit-testing - karma中如何模拟mock服务失败?

转载 作者:搜寻专家 更新时间:2023-10-30 21:40:53 24 4
gpt4 key购买 nike

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()

最佳答案

您应该使用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

另请参阅:

关于unit-testing - karma中如何模拟mock服务失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40654271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com