I'm trying to test an observable that is bound to an inline property rather than a method on a service, however I can't seem to find any examples about how to return the correct value either in the SpyObj itself or through a spyOn/SpyOnProperty call.
// 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>;
});
I've seen a couple of examples about using spyOnProperty with get and set methods but that's not what's happening here, am I declaring it incorrectly on the jasmine.SpyObj or is there a particular jasmine method that I'm missing to return the desired value from the content$
What I do in these scenarios is I add an instance property to the createSpyObj
itself.
// 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>;
});
Later on, if you want to change the value of content$
, you can do mockContent$.next(/* new mock content goes here*/);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.