我正在尝试测试绑定到内联属性而不是服务上的方法的observable,但是我似乎找不到任何关于如何在SpyObj本身或通过spyOn/SpyOnProperty调用返回正确值的示例。
// ContentService
readonly content$ = this.http.get('www.testContent.com');
// ParentService
constructor(private readonly contentService: ContentService){
this.loadContent();
}
// This could return different content dependent on locale for example
loadContent(){
this.contentService.content$.subscribe((response)=>{
// Handle response
})
}
// Unit test
let service: ParentService;
let contentServiceSpy: jasmine.SpyObj<ContentService>;
beforeEach(() => {
const spy = jasmine.createSpyObj('ContentService', [], {
// Returns cannot read subscribe of undefined
content$: of()
});
TestBed.configureTestingModule({
providers: [
ParentService,
{ provide: ContentService, useValue: spy }
]
});
service = TestBed.get(ParentService);
contentServiceSpy = TestBed.get(ContentService) as jasmine.SpyObj<ContentService>;
});我已经看到了几个关于在get和set方法中使用spyOnProperty的示例,但这并不是这里发生的事情,是我在jasmine.SpyObj上错误地声明了它,还是缺少一个特定的jasmine方法来从content$返回所需的值
发布于 2020-05-20 01:10:12
在这些场景中,我所做的是向createSpyObj本身添加一个实例属性。
// Unit test
let service: ParentService;
let contentServiceSpy: jasmine.SpyObj<ContentService>;
let mockContent$ = new BehaviorSubject(/* content mock goes here*/);
beforeEach(() => {
const spy = jasmine.createSpyObj('ContentService', ['loadContent']);
spy.content$ = mockContent$; // add the instance property itself
TestBed.configureTestingModule({
providers: [
ParentService,
{ provide: ValueService, useValue: spy }
]
});
service = TestBed.get(ParentService);
contentServiceSpy = TestBed.get(ContentService) as jasmine.SpyObj<ContentService>;
});稍后,如果您想要更改content$的值,可以执行mockContent$.next(/* new mock content goes here*/);
https://stackoverflow.com/questions/61896576
复制相似问题