使用 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 方法一起使用的示例,但这不是这里发生的事情,我在茉莉花上声明得不正确吗?SpyObj 或者我是否缺少一个特定的茉莉花方法来从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*/);

最新更新