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();
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With