我想测试服务中的功能。但是我无法测试订阅。 我该怎么办?
要测试的功能:
getInvestigates(page, lim): any {
return this.http.get(`${this.bcUrl}/api/investigates?page=${page}&size=${lim}`, this.httpOptions)
.subscribe(
(data: DataInterface) => {
this.investigates = data.content;
this.st.totalPages = data.totalPages;
this.st.totalElements = data.totalElements;
},
error => {
if (error.status === 404) {
alert('Not found');
}
});
}
答案 0 :(得分:1)
找到了如何测试此功能的方法。但是仍然无法测试错误。
error => {
if (error.status === 404) {
alert('Not found');
}
规格:
it('should get investigate', inject([InvestigateService, HttpTestingController],
(service: InvestigateService, backend: HttpTestingController) => {
const mockInvestigates = {
'content':
{
'id': 6,
'investigateType': 'WARN',
'number': '12018150030005555',
'investigatePriority': 'NORMAL',
'investigateStatus': 'OPEN',
'correction': {
'create': 1527454800,
'action': 'CREATE',
'user_id': 6
},
'hide': false,
'tags': [
{
'id': 1,
'name': 'Кражи',
'correction': {
'action': 'UPDATE',
'user_id': 1
}
}
],
}};
service.getInvestigates(1, 1);
backend.expectOne({
method: 'GET',
url: 'http://30.30.0.101:8080/api/investigates?page=1&size=1'
}).flush(mockInvestigates);
expect(service.investigates).toBe(mockInvestigates.content);
}));
认为我应该在函数中添加公共错误并创建模拟函数,该函数会返回模拟调查或错误?
类似这样的东西。
class InvestigatesStub {
public error = false;
mockGetInvestigates() {
if (this.error) {
return Observable.throw(new Error('Test error'));
} else {
return Observable.from(data);
}
}
}
答案 1 :(得分:1)
it('should not get investigate if error', inject([InvestigateService,
HttpTestingController],
(service: InvestigateService, backend: HttpTestingController) => {
service.getInvestigates(1, 1);
backend.expectOne({
method: 'GET',
url: 'http://30.30.0.101:8080/api/investigates?page=1&size=1'
}).flush(null, {status: 404, statusText: 'Not Found'});
expect(service.investigates).toBeFalsy();
}));