简体   繁体   中英

Jasmine angular unit testing BehaviorSubject

i have some service like this

calendar-domain.service.ts

@Injectable()
export class CalendarDomainService {
  private _calendarWeek = new BehaviorSubject<CalendarWeekTo | null>(null);
  get calendarWeek$(): Observable<CalendarWeekTo | null> {
    return this._calendarWeek.asObservable();
  }

  setCalendarWeek(calendarWeek: CalendarWeekTo): void {
    this._calendarWeek.next(calendarWeek);
  }
}

And unit test like this

calendar-domain.service.spec.ts

import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { TestBed } from '@angular/core/testing';

import { CalendarDomainService } from './calendar-domain.service';

describe('CalendarDomainService', () => {
    let service: CalendarDomainService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [CalendarDomainService],
            schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
        });
        service = TestBed.inject(CalendarDomainService);
    });

    it('should be created', () => {
        expect(service).toBeTruthy();
    });
});

As you may see i didn't test those two function, because honest I don't know how even to start testing, any info about how to start, thanks

You can use the done Callback on the test itself and subscribe normally to the subject.

it('Should emit next value of the week', (done)=>{
   service.setCalendarWeek(<yourvaluehere>);
   service.calendarWeek$.subscribe(v=> {
     expect(v).toBe(<yourvaluehere>)
     done();
   });
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM