I am trying to mock out a service dependency inside a component test, this service has a behaviour subject property which I'm trying to mock.
My service is as follows:
export class DatePickerService {
public date: moment.Moment;
public selectedDate: BehaviorSubject<moment.Moment> = new BehaviorSubject<moment.Moment>(moment());
public changeDate = (date: moment.Moment) => {
this.selectedDate.next(date);
}
}
The selectedDate is then subscribed to in my component:
ngOnInit() {
this.datePickerService.selectedDate.subscribe((selectedDate) => {
// do stuff here...
}
}
When it comes to testing my component, I am using the TestBed approach and supplying my own mock for the date picker service:
const mockDatePickerService = {
selectedDate: jasmine.createSpy().and.returnValue(of(moment('01-01-2018', 'DD-MM-YYYY')))
};
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
MyComponent
],
providers: [
HttpClient,
HttpHandler,
{ provide: DatePickerService, useValue: mockDatePickerService }
],
imports: [
TranslateModule.forRoot(),
RouterTestingModule
]
})
.compileComponents();
}));
On trying to run my first test, I get an error from the
TypeError: undefined is not a constructor (evaluating 'this.datePickerService.selectedDate.subscribe')
If I log out the value of my service in the component's onInit, I do see my mock:
LOG: Object{selectedDate: function () { ... }}
So I'm unsure why i am seeing this undefined error, I am wondering if its my use of jasmine and the returnValue with the of invocation?
Anyone got any ideas please?
Thanks