j.2bb
j.2bb

Reputation: 911

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

Upvotes: 5

Views: 3193

Answers (2)

j.2bb
j.2bb

Reputation: 911

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

Upvotes: 11

Karolke
Karolke

Reputation: 103

Did you imported jquery?

declare var jquery:any;   // not required
declare var $ :any;   // not required

Upvotes: 0

Related Questions