Mocking a BehaviourSubject in a component test spec

浪尽此生 提交于 2020-04-10 06:15:24

问题


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:


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);
});


来源:https://stackoverflow.com/questions/52365801/mocking-a-behavioursubject-in-a-component-test-spec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!