gpt4 book ai didi

angular - 使用 createSpyObj 对可观察量进行单元测试

转载 作者:行者123 更新时间:2023-12-02 20:09:41 25 4
gpt4 key购买 nike

我有一个函数调用另一个本身使用 http 订阅的函数,但我在测试它时遇到了问题...

我的组件

id = 1;

myFunct() {
this.myService.delete(this.id);
}

我的服务

delete(id) {
this.http.delete(this.myUrl + '/' + id).subscribe()
}

测试

let mockService;

beforeEach(() => {
TestBed.configureTestingModule({
mockService = createSpyObj(['delete']);

imports: ...,
declarations: ...,
providers: [
{provide: MyService, useValue: mockService}
]
}).compileComponents();

fixture = ...;
component = ...;
fixture.detectChanges();
});

it('should test delete', () => {
mockService.delete.and.returnValue({ subscribe: () => {} });
component.myFunct();
expect(mockService.delete).toHaveBeenCalledTimes(1);
});

我的测试返回错误:

Cannot read property 'subscribe' of undefined

最佳答案

常见的模式是从你的服务方法返回可观察的并在内部订阅,例如。成分。

类似这样的:

我的组件

 id = 1;

myFunct() {
this.myService.delete(this.id).subscribe(
(result) => console.log(result),
(error) => console.log(error)
};

我的服务

 delete(id): Observable<any> {
this.http.delete(this.myUrl + '/' + id)
}

测试

imports {of} from 'rxjs'

let mockService;

beforeEach(() => {
TestBed.configureTestingModule({
mockService = createSpyObj(['delete']);

imports: ...,
declarations: ...,
providers: [
{provide: MyService, useValue: mockService}
]
}).compileComponents();

fixture = ...;
component = ...;
fixture.detectChanges();
});

it('should test delete', () => {
mockService.delete.and.returnValue(of({id: 1}));
component.myFunct();
expect(mockService.delete).toHaveBeenCalledTimes(1);
});

关于angular - 使用 createSpyObj 对可观察量进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53867825/

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