[英]Testing an observable on a service property using jasmine.SpyObj - Angular/Jasmine
我正在尝试测试绑定到内联属性而不是服务上的方法的可观察对象,但是我似乎找不到任何关于如何在 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>;
});
我已经看到了一些关于将 spyOnProperty 与 get 和 set 方法一起使用的示例,但这不是这里发生的事情,我是否在 jasmine.SpyObj 上错误地声明它,或者是否存在我缺少的特定 jasmine 方法来返回所需的值从content$
我在这些场景中所做的就是向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*/);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.