unit-testingjasmineangular6karma-jasminebootstrap-daterangepicker

How to handle bootstrap-daterangepicker in angular component unit test?


I am trying to write a unit test of an angular 6 component which is initializing the bootstrap-daterangepicker in the ngAfterViewInit() method. When I run my unit test it gives the following error:

TypeError: $(...).daterangepicker is not a function

this is the code from the actual component(EmployeeComponent):

ngAfterViewInit(): void {
    this.initializeDatePicker(this);
  }

initializeDatePicker(that: any) {
    const start = moment().subtract(7, 'days');
    const end = moment();

    $('#reportrange').daterangepicker({
      startDate: start,
      endDate: end,
      maxDate: moment(),
      ranges: {
        'Today': [moment(), moment()],
        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')]
      }
    }, cb);
    cb(start, end);
  }

this is the code from my test class:

        describe('EmployeeComponent', () => {
  let component: EmployeeComponent;
  let fixture: ComponentFixture<EmployeeComponent>;
  let messageService: NotificationService;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [EmployeeComponent]
    })
      .overrideComponent(EmployeeComponent, {
        set: {
          template: '',
          providers: [
            { provide: NotificationService, useValue: messageService },
            { provide: ActivatedRoute, useValue: { queryParams: of({ emp: "123" }) } }
          ]
        }
      })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(EmployeeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

Solution

  • You don't need to handle it in your test cases. That component should be initialized in a separate service and you can simply mock that method from the service. In the way you can avoid this error.

    let say you move all the code of the initializeDatePicker() in a method in some service let say common-service.ts and you can simply call that service from this method like

    this.commonServiceObj.initializeDatePicker();
    

    Now after doing this, you can simply mock initializeDatePicker() from the service object and error should be gone.