Mocking a BehaviourSubject in a component test spec

Viewed 14535

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

1 Answers

If I were you, I would use the same object as my service uses, and control it however I want.

Here is an example :

const subjectMock = new BehaviorSubject<moment.Moment>(undefined),
const mockDatePickerService = {      
  selectedDate: subjectMock.asObservable()
};

Now, you provide it as you did, and in your tests, you can simply do this (this is an example, not a test you must do) :

it('changeDate should call subject.next', () => {
  const value = 'Moment value here';
  subjectMock
    .pipe(filter(res => !!res))
    .subscribe(res => expect(res).toEqual(value));

  subjectMock.next(value);
});
Related