Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 : How to import jQuery in Jest test?

I have an angular component that use a CalendarService. When the component is init, I call a "calendarService.init()" method.

This CalendarService set the configuration of a semantic-ui-calendar (base on jQuery), with a code like "$(myElement).calendar(settings);".

When I test my component with Jest, the initialization of the component has an error : "ReferenceError: $ is not defined".

How can i fix it ?

search.component.spec.ts :

describe('SearchComponent', () => {

  let fixture: ComponentFixture<SearchComponent>;
  let component: SearchComponent;
  let element: DebugElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        AppModule
      ],
      providers: [
        { provide: APP_BASE_HREF, useValue : '/search' },
        CalendarService
      ]
    });

    fixture = TestBed.createComponent(SearchComponent);

    let calendarService = TestBed.get(CalendarService);

    component = fixture.componentInstance;
    element = fixture.debugElement;

    fixture.detectChanges();
  }));
});

search.component.ts :

@Component({
  selector: 'afo-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.less']
})
export class SearchComponent implements OnInit, AfterViewInit {

  constructor(private calendarService: CalendarService) { }

  ngOnInit() {
  }

  ngAfterViewInit() {
    this.calendarService.init();
  }

}

calendar.service.ts :

@Injectable()
export class CalendarService {

  constructor() {
  }

  init() {
    $('.ui.calendar.field').calendar();
  }
}
like image 864
j.2bb Avatar asked Jan 28 '23 16:01

j.2bb


1 Answers

I found the solution :

I need to add the followings lines in my setupJest.ts :

import * as $ from 'jquery';
Object.defineProperty(window, '$', {value: $});
Object.defineProperty(global, '$', {value: $});
Object.defineProperty(global, 'jQuery', {value: $});

At the begining, I tried this solution :

import $ from 'jquery';
window.$ = $;
global.$ = global.jQuery = $;

But global.xxx and window.xxx were unknown.

See :

https://github.com/thymikee/jest-preset-angular#allow-vendor-libraries-like-jquery-etc

https://github.com/facebook/jest/issues/708

like image 177
j.2bb Avatar answered Jan 31 '23 08:01

j.2bb