我正在尝试为角度服务编写测试,该服务具有Subject属性和调用.next()该主题的方法.
该服务如下:
@Injectable()
export class SubjectService {
serviceSubjectProperty$: Subject<any> = new Subject();
callNextOnSubject(data: any) {
this.serviceSubjectProperty$.next(data);
}
}
Run Code Online (Sandbox Code Playgroud)
以及该服务的测试文件:
import { TestBed, inject } from '@angular/core/testing';
import { SubjectService } from './subject.service';
describe('SubjectService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
SubjectService
]
});
});
it('callNextOnSubject() should emit data to serviceSubjectProperty$ Subject',
inject([SubjectService], (subjectService) => {
subjectService.callNextOnSubject('test');
subjectServiceProperty$.subscribe((message) => {
expect(message).toBe('test');
})
}));
});
Run Code Online (Sandbox Code Playgroud)
如果我将subjectService.callNextOnSubjectfrom 的参数更改'test'为其他任何内容,则测试始终会传递事件.
我也尝试用async和包装所有东西fakeAsync,但结果是一样的.
测试是否callNextOnSubject …
我正在使用observables和flatMap运算符,我编写了一个方法,它调用并调用API并返回带有对象数组的observable.基本上我需要的是获取对象数组并处理每个对象,在处理完所有项之后,我想链接结果以使用我编写的另一个方法进行额外的API调用.以下代码可以满足我的需求:
this.apiService.getInformation('api-query', null).first().flatMap((apiData) => {
return apiData;
}).subscribe((dataObject) => {
this.processService.processFirstCall(dataObject);
}, null, () => {
this.apiService.getInformation('another-query', null).first().subscribe((anotherQueryData) => {
this.processService.processSecondCall(anotherQueryData);
});
});
Run Code Online (Sandbox Code Playgroud)
但是从我的角度来看,这种方法并不是最优的,我想使用flatMap来链接这些调用,但如果我执行以下操作
this.apiService.getInformation('api-query', null).first().flatMap((apiData) => {
return apiData;
}).flatMap((dataObject) => {
this.processService.processFirstCall(dataObject);
return [dataObject];
}).flatMap((value) => {
return this.apiService.getInformation('another-api-query', null).first();
}).subscribe((value) => {
this.processService.processSecondCall(value);
});
Run Code Online (Sandbox Code Playgroud)
第二个API调用对apiData对象数组上的每个项执行一次.我知道我错过了或误解了什么.但是从这个帖子的第二个答案为什么我们需要使用flatMap?我认为第二个flatMap应该返回已处理的apiData,而是返回该Array上的每个对象项.我很感激你的帮助.
谢谢.